Sub topic 5
Writing and Appending Text
This chapter covers writing text to files with write() and writelines(), and choosing between overwriting and appending. It assumes you know basic Python syntax, the difference between str and bytes, and try/except. It also assumes you have seen file modes and the with statement.
Write mode replaces the file
Opening a file with mode "w" creates it if it does not exist. If it does exist, Python truncates it to zero length at the moment open() returns, before you write anything. A crash right after open() leaves you with an empty file.
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("first line\n")
f.writelines(["second line\n", "third line\n"])Always pass encoding explicitly. Without it, Python uses a platform-dependent default, so the same script can write different bytes on different machines.
write() and writelines()
write(s) takes one str and returns the number of characters written. It does not add a newline, so you must include "\n" yourself.
writelines(iterable) takes any iterable of strings and writes each one. Despite the name, it does not add line endings either.
lines = ["alpha", "beta", "gamma"]
with open("letters.txt", "w", encoding="utf-8") as f:
count = f.write("header\n")
print(count) # 7
f.writelines(line + "\n" for line in lines)Passing a non-string, such as an int, raises TypeError. Convert values first with str() or an f-string.
with open("scores.txt", "w", encoding="utf-8") as f:
for name, score in [("Ada", 91), ("Linus", 84)]:
f.write(f"{name}: {score}\n")Appending with mode "a"
Mode "a" opens the file for writing and positions every write at the end. Existing content stays. If the file does not exist, it is created.
with open("notes.txt", "a", encoding="utf-8") as f:
f.write("appended line\n")In append mode, writes always go to the end of the file, even if you call seek() first. This makes "a" the right choice for logs.
| Mode | File exists | File missing | Existing content |
|---|---|---|---|
| `"w"` | Truncated | Created | Lost |
| `"a"` | Opened at end | Created | Kept |
| `"x"` | `FileExistsError` | Created | Not applicable |
Use "x" when overwriting would be a bug and you want Python to refuse instead.
try:
with open("report.txt", "x", encoding="utf-8") as f:
f.write("new report\n")
except FileExistsError:
print("report.txt already exists, not overwriting")Buffering and when data reaches the disk
Python collects written text in a buffer and writes it to the operating system in larger pieces. Data you wrote may not be on disk yet when write() returns. Leaving the with block flushes the buffer and closes the file.
You can force the buffer out earlier with flush(). This matters when another process reads the file while your program is still running.
import time
with open("progress.log", "a", encoding="utf-8") as f:
for step in range(3):
f.write(f"step {step} done\n")
f.flush()
time.sleep(1)flush() hands data to the operating system. It does not guarantee the data is physically on disk. That guarantee needs os.fsync(), which a later chapter on safe writes covers.
Common errors
- Forgetting newlines.
f.write("a")followed byf.write("b")producesabon one line. - Using
"w"when you meant"a". Each run silently erases earlier output. - Writing inside a loop that reopens the file. Opening with
"w"on every iteration keeps only the last item. Open the file once, outside the loop. - Writing bytes to a text file.
f.write(b"abc")raisesTypeError. Use"wb"for bytes. - Reading from a write-only file.
f.read()on a file opened with"w"raisesio.UnsupportedOperation.
Verifying what you wrote
A quick round trip confirms the result. This example shows the difference between "w" and "a" across two runs of the same code.
for mode in ("w", "a"):
with open("demo.txt", mode, encoding="utf-8") as f:
f.write(f"written with {mode}\n")
with open("demo.txt", encoding="utf-8") as f:
print(f.read())The output is written with w followed by written with a. The first pass creates or truncates the file, and the second adds to it. Running the script again gives the same output, because the "w" pass resets the file each time.
Exercise
A script runs once a day and should add one line with the date to history.txt, keeping all earlier lines. A colleague wrote open("history.txt", "w", encoding="utf-8"). What goes wrong, and what is the fix?
Show answer
Mode "w" truncates the file each time it is opened, so only the latest day's line survives. Change the mode to "a" so each run appends to the end and earlier lines are kept. Also make sure the written string ends with "\n" so each date lands on its own line.
Exercise
What is the content of out.txt after this code runs? with open("out.txt", "w", encoding="utf-8") as f: f.write("a"); f.write("b"); f.writelines(["c", "d"])
Show answer
The file contains abcd on a single line. Neither write() nor writelines() adds a newline, so the pieces are joined with nothing between them.