Python Write to File: write() and Append Mode
Write to a File with write()
The write() method puts text into a file that's open in mode "w" or "a". It writes exactly the string you give it, nothing more.
Think of it like writing in a notebook with a pen. Only the words you write end up on the page. The notebook doesn't add a full stop, a space or a new line for you.
The rules
f.write(text)takes one string.- It writes nothing on the screen. To see the text, read the file back.
- Numbers must become text first:
str(25), or an f-string likef"{score}"(chapter 5). - You can call
write()many times before you close the file. Each call carries on where the last one stopped.
name = "Sunny"
score = 92
f = open("result.txt", "w")
f.write(name)
f.write(" scored ")
f.write(str(score))
f.close()
f = open("result.txt")
print(f.read())
f.close()Sunny scored 92
Three write() calls, one line of text: each piece goes right after the one before.
Avoid: writing a number
f = open("result.txt", "w")
f.write(92)
f.close()TypeError: write() argument must be str, not int
Don't worry, the message tells you the fix. write() wants a str (a string), and you gave it an int.
Good: turn it into text first
score = 92
f = open("result.txt", "w")
f.write(f"Score: {score}")
f.close()
f = open("result.txt")
print(f.read())
f.close()Score: 92
An f-string builds the whole text in one go, with the number inside. That's usually the neatest way.
Common beginner doubt: "print() takes many values with commas. Does write()?" No. f.write("Sunny", "Rocky") gives a TypeError. Join the pieces into one string first, with + or an f-string.
write() puts one string into the file, exactly as you give it. Turn numbers into text first.