Python Write Files
Tutorial 36 of 65 · pythondeck.com Python course
Open with w to overwrite, a to append, x to create exclusively. write() writes a string, writelines() writes an iterable of strings (no newlines added). For binary use the b mode flag.
Writing persists results: reports, caches, user exports. Mode "w" truncates existing files; "a" appends. Create parent directories with Path.mkdir(parents=True, exist_ok=True) when your layout requires nested folders.
Concurrent writers need coordination—file locks, a database, or a queue—not blind overwrite of the same path from multiple processes.
write() and writelines() on text and binary streams.
Path.write_text / write_bytes for atomic-ish small writes.
Append mode "a" and line-ending discipline (\n vs os.linesep).
Flushing and f.flush() before other processes read partial output.
JSON/CSV writers: json.dump, csv.writer with newline="" for CSV.
Atomic replace pattern: write temp file, then os.replace.
CSV on Windows requires open(..., newline="") so the csv module controls newlines. Pretty-printed JSON uses indent=; production pipelines often use compact one-line records per row in NDJSON.
Buffering means data may not hit disk until the file closes—use with blocks or flush() when subprocesses must read incomplete output. For critical durability, os.fsync(f.fileno()) after flush (with performance cost).
Never write secrets world-readable; set permissions with os.chmod on Unix or appropriate ACLs on Windows.
Log rotation and append-only audit trails are common reasons to open with "a"; document newline and encoding expectations so downstream parsers stay reliable.
Truncating files with "w" when "a" or exclusive create ("x") was intended.
Forgetting newline="" when using the csv module on Windows.
Assuming a write succeeded without checking exceptions or disk full errors.
Writing sensitive data to predictable temp paths without cleanup.
Two processes overwriting the same file without locking.
Use context managers; create parent dirs explicitly when needed.
Use atomic write (temp + replace) for config and state files.
Pick text vs binary and encoding once per pipeline; document the format.
Set restrictive permissions on files containing credentials or tokens.
Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.
The program below demonstrates write text. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# Example: Write text
# Run in the REPL or save as a .py file and execute with python.
lines = ["alpha", "beta", "gamma"]
with open("words.txt", "w") as f:
f.write("\n".join(lines))
This sample walks through append in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# Example: Append
# Run in the REPL or save as a .py file and execute with python.
with open("words.txt", "a") as f:
f.write("\ndelta")
Here is a hands-on illustration of write csv. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.
# Example: Write CSV
# Run in the REPL or save as a .py file and execute with python.
import csv
rows = [["name", "score"], ["Ada", 99], ["Grace", 97]]
with open("out.csv", "w", newline="") as f:
csv.writer(f).writerows(rows)
The program below demonstrates write lines. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# Write text line-by-line to avoid huge single strings
from pathlib import Path # for size check below
lines = ["first\n", "second\n", "third\n"] # prepared lines
with open("out.txt", "w", encoding="utf-8") as fh: # truncate/create
fh.writelines(lines) # write sequence
with open("out.txt", "a", encoding="utf-8") as fh: # append mode
fh.write("fourth\n") # add one more line
with open("out.txt", encoding="utf-8") as fh: # read back
print(fh.read(), end="") # verify contents
print(Path("out.txt").stat().st_size) # bytes on disk
This sample walks through csv writer in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# csv.writer emits proper escaping for commas/quotes
import csv # CSV module
rows = [["name", "score"], ["Ada", 99], ["Grace", 97]] # table
with open("scores.csv", "w", newline="", encoding="utf-8") as fh: # csv-safe newline
writer = csv.writer(fh) # row writer
writer.writerows(rows) # all rows at once
with open("scores.csv", encoding="utf-8") as fh: # read result
print(fh.read()) # comma-separated text
from pathlib import Path # pathlib import for size check
print(Path("scores.csv").exists()) # True