How to write to a file in Python
Open with mode='w' (overwrite) or 'a' (append) inside a with-block. Always pass encoding='utf-8'.
with open("output.txt", "w", encoding="utf-8") as f:
f.write("first line\n")
f.write("second line\n")'w' truncates the file if it exists β every open with 'w' starts from an empty file. 'a' appends to the end of an existing file (creating it if it doesn't exist). Use 'x' for 'create-and-fail-if-exists' when you want to guard against overwriting.
Always use the with-block: on exit (normal or exception) it flushes the write buffer and closes the file handle. Forgetting to close means the last few writes may be lost if the process crashes.
encoding='utf-8' is the safe default. The platform default is not portable β Windows opens as cp1252 without this argument, which silently mangles anything above ASCII.
Variations
Write a list of lines
lines = ["one\n", "two\n", "three\n"]
with open("out.txt", "w", encoding="utf-8") as f:
f.writelines(lines)writelines does NOT add newlines β include them in each string.
Append instead of overwrite
with open("log.txt", "a", encoding="utf-8") as f:
f.write("new line\n")'a' creates the file if it doesn't exist yet.
Atomic write (safer for prod)
import os, tempfile
fd, tmp = tempfile.mkstemp(dir=".")
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write("payload\n")
os.replace(tmp, "final.txt")os.replace is atomic β either fully old or fully new, never a half-written state.
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.