Writing to a file is as simple as reading it, but it has a couple of details worth knowing.
write()
with open("output.txt", "w", encoding="utf-8") as f:
f.write("First line\n")
f.write("Second line\n")
write writes exactly what you give it, without adding line breaks. If you do not put \n, everything ends up on a single line. And it only accepts text: to write a number you must convert it with str() or an f-string.
with open("output.txt", "w", encoding="utf-8") as f:
f.write(str(42) + "\n")
f.write(f"Total: {3 * 7}\n")
print() with file=
You can also use print, which adds the line break by itself:
with open("output.txt", "w", encoding="utf-8") as f:
print("Hello", file=f)
print("Goodbye", file=f)
Mode "w": careful, it deletes
Every time you open with "w", the file is emptied before writing. Perfect to generate a new file; dangerous if you wanted to keep the previous content.
with open("output.txt", "w", encoding="utf-8") as f:
f.write("one\n")
with open("output.txt", "w", encoding="utf-8") as f:
f.write("two\n")
# output.txt contains only: two
It is what happens in Write to a text file: the previous content is replaced.
Mode "a": appending at the end
with open("log.txt", "a", encoding="utf-8") as f:
f.write("New entry\n")
Each run adds one more line without losing the previous ones. It is the mode for logs and the basis of Appending to a text file.
Reading an input and saving it
A very common pattern: ask the user for lines until they type an empty one and save them all:
with open("output.txt", "w", encoding="utf-8") as f:
line = input()
while line != "":
f.write(line + "\n")
line = input()
Two files at once
You can open several with a single with, separated by commas. It is what you need to read one and write another:
with open("source.txt", "r", encoding="utf-8") as source, open("target.txt", "w", encoding="utf-8") as target:
for line in source:
target.write(line.upper())
It is the structure of Convert a text file to uppercase and Reverse text from a file.
The data only reaches the disk on closing
Python keeps what is written in an intermediate buffer and dumps it to the file when it is closed. That is why with matters: if the program ends without closing, part of the text could be lost.