Python Writing Files
In this page:
Writing Text to Files
f.write(text) writes a string to an open file and returns the number of characters written -- opening a file in w mode first truncates any existing content, so writing to a file that already has data will completely replace it, not append to it.
Example: Writing Text to Files
with open("output.txt", "w") as f:
f.write("first version")
with open("output.txt", "w") as f:
f.write("replaced content") # 'w' truncates first
with open("output.txt") as f:
print(f.read())
Writing Multiple Lines
f.writelines(list_of_strings) writes multiple strings at once from any iterable, but unlike print() it does not add newlines between them automatically -- each string in your list needs its own trailing '\n' if you want them on separate lines.
Example: Writing Multiple Lines
lines = ["first\n", "second\n"]
with open("output.txt", "w") as f:
f.writelines(lines)
with open("output.txt") as f:
print(f.read())
Appending Data to Files
Opening a file with mode a instead of w preserves everything already in the file and writes new content starting at the end -- this is the mode you want for things like log files that should accumulate entries across many runs rather than being wiped each time.
Example: Appending Data to Files
with open("log.txt", "w") as f:
f.write("run 1\n")
with open("log.txt", "a") as f:
f.write("run 2\n")
with open("log.txt") as f:
print(f.read())
Writing Non-String Data
write() only accepts strings, so writing a number or a list directly raises a TypeError -- you need to convert it first with str(value) (or use json.dump() for structured data) before passing it to write().
Example: Writing Non-String Data
count = 42
with open("output.txt", "w") as f:
f.write(str(count))
with open("output.txt") as f:
print(f.read())
Flushing Buffers
Python buffers written data in memory before actually pushing it to disk for performance reasons, which means data isn't necessarily saved the instant you call write() -- f.flush() forces an immediate write to disk, and closing the file (or exiting a with block) flushes automatically.
Example: Flushing Buffers
with open("output.txt", "w") as f:
f.write("buffered data")
f.flush()
print("Flushed to disk before the block even ends")
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: