- Courses
- 💻Programming Languages
- 🐍Python
- File Handling & Persistence
- Writing Files
On this page
How to Write to a File in Python
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Writing to files in Python is built on a single function — open() — combined with a mode string that controls what happens when the file is opened. The correct pattern is to open the file inside a with statement, write your content, and let Python close and flush the file automatically. This lesson covers every write mode, every writing method, newline and encoding behaviour, binary writing, structured formats, pathlib, large file techniques, and the error handling patterns production code requires.
File Modes for Writing
Every call to open() requires a mode argument. The following modes are relevant for writing:
ModeCreates file if missingEffect on existing contentUse case"w"YesTruncates (erases all content)Overwrite or create fresh"a"YesPreserves content, writes at endLogs, incremental output"x"YesRaises FileExistsErrorSafe creation — never overwrite"wb"YesTruncatesWrite raw binary data"ab"YesPreserves, appends binaryAppend binary data"r+"NoPreserves, writes at cursorRead and write existing file"w+"YesTruncatesRead and write, start fresh
The most commonly used modes are "w", "a", and "x" for text, and "wb" for binary. Choose the mode based on a single question: what should happen to the file if it already exists?
The with open() Pattern — Always Use This
The with statement is a context manager. When the indented block ends — whether normally or because an exception was raised — Python calls f.close() automatically. This flushes the internal write buffer and releases the file handle:
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello, world!\n")
# File is guaranteed to be closed and flushed here
Without with, you must call f.close() manually. If an exception occurs before that call, the file stays open and your data may not be flushed to disk:
# Fragile — data loss risk if an exception occurs
f = open("output.txt", "w", encoding="utf-8")
f.write("Hello, world!\n")
f.close() # May never execute
Always use with open(...). There is no situation in standard Python where manual open() / close() is preferable.
Always Specify encoding
When opening a text file, always pass encoding="utf-8" explicitly. Omitting it causes Python to use the operating system's default encoding, which is cp1252 on Windows and utf-8 on most Linux and macOS systems. Code that works on one platform silently breaks on the other:
# Platform-dependent — may produce different files on Windows vs Linux
with open("data.txt", "w") as f:
f.write("Ångström\n")
# Explicit and portable — produces identical output on every platform
with open("data.txt", "w", encoding="utf-8") as f:
f.write("Ångström\n")
"utf-8" is the correct default for new files. The only reason to use a different encoding is when a downstream system explicitly requires one (e.g., "latin-1" for legacy Windows software or "utf-8-sig" for CSV files opened in Microsoft Excel on Windows).
Writing Text with .write()
.write() writes a single string to the file exactly as given. It returns the number of characters written. It does not add a newline character — you must include \n manually wherever a line break is required:
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("First line\n")
f.write("Second line\n")
f.write("Third line\n")
Calling .write() multiple times is perfectly efficient. Each call appends to the current stream position within the open file handle — there is no overhead from opening the file multiple times.
Writing a formatted string using f-strings is the most readable approach for variable content:
name = "Alice"
score = 98.5
with open("report.txt", "w", encoding="utf-8") as f:
f.write(f"Student: {name}\n")
f.write(f"Score: {score:.1f}\n")
f.write(f"Grade: {'A' if score >= 90 else 'B'}\n")
Writing Multiple Lines with .writelines()
.writelines() accepts an iterable of strings and writes each one to the file sequentially. Like .write(), it does not add newline characters between elements — each string in the iterable must already include \n where needed:
lines = [
"Alpha\n",
"Beta\n",
"Gamma\n",
]
with open("list.txt", "w", encoding="utf-8") as f:
f.writelines(lines)
The resulting file is identical to calling .write() once per element in a loop. .writelines() is not faster than a loop — it is simply more concise when your data is already a list of complete line strings.
Adding newlines automatically using a generator expression avoids polluting the source list with \n characters:
items = ["Alpha", "Beta", "Gamma"]
with open("list.txt", "w", encoding="utf-8") as f:
f.writelines(item + "\n" for item in items)
Using str.join() for a single write call — when the entire content fits comfortably in memory, building the string first and writing it once is clean and explicit:
items = ["Alpha", "Beta", "Gamma"]
content = "\n".join(items) + "\n"
with open("list.txt", "w", encoding="utf-8") as f:
f.write(content)
Write Mode ("w") — Overwrite an Existing File
Opening a file in "w" mode truncates it immediately — even before you write a single character. If the file exists, its previous content is gone as soon as open() succeeds:
# First run — creates the file
with open("config.txt", "w", encoding="utf-8") as f:
f.write("version=1\n")
# Second run — previous content is erased, not appended
with open("config.txt", "w", encoding="utf-8") as f:
f.write("version=2\n")
# config.txt now contains only "version=2"
This behaviour is intentional and useful for regenerating output files — reports, exports, compiled results — where you always want a clean slate. It is dangerous when you intend to add to an existing file, which is what "a" mode is for.
Append Mode ("a") — Add to an Existing File
"a" mode opens the file with the cursor positioned at the end. Every .write() call adds content after all existing content, regardless of what is already there:
with open("events.log", "a", encoding="utf-8") as f:
f.write("2026-05-31 09:00 — Server started\n")
Appending is idempotent with respect to existing content — it cannot accidentally erase what is already in the file. It is the correct mode for log files, audit trails, and any output that accumulates over time.
If the file does not exist, "a" creates it — the same behaviour as "w".
Exclusive Creation Mode ("x") — Safe File Creation
"x" mode creates a new file and raises FileExistsError immediately if a file with that name already exists. No truncation, no partial write — the operation fails before the file is touched:
try:
with open("invoice_0042.txt", "x", encoding="utf-8") as f:
f.write("Invoice data\n")
except FileExistsError:
print("invoice_0042.txt already exists — refusing to overwrite.")
Use "x" mode whenever creating a file that must not replace an existing one: unique report files named by ID or timestamp, lock files, one-time configuration files, or any situation where silently overwriting would cause data loss.
Read-Write Modes: "r+" and "w+"
Some workflows require both reading and writing within the same open file handle. Python provides two combined modes:
"r+" — read and write without truncating. The file must already exist. The cursor starts at position 0:
with open("config.txt", "r+", encoding="utf-8") as f:
content = f.read() # Read existing content
f.seek(0) # Move cursor back to beginning
f.write(content.upper()) # Overwrite with modified content
f.truncate() # Remove any leftover bytes from old content
"w+" — read and write, truncating first. Creates the file if missing. Useful when you need to write content and then immediately read it back without reopening:
with open("temp.txt", "w+", encoding="utf-8") as f:
f.write("temporary data\n")
f.seek(0) # Rewind to the beginning
content = f.read() # Read back what was just written
print(content)
.seek() and .tell() — Controlling Stream Position
.tell() returns the current byte position of the file cursor. .seek(offset) moves the cursor to a specific byte position. These are essential for "r+" and "w+" workflows:
with open("data.txt", "r+", encoding="utf-8") as f:
print(f.tell()) # 0 — at the beginning
f.write("Header\n")
print(f.tell()) # 7 — after writing 7 bytes
f.seek(0) # Back to the beginning
print(f.read()) # Reads the entire file including what was written
.seek(0, 2) moves to the end of the file (useful for appending in "r+" mode). .seek(0) rewinds to the beginning. .truncate() truncates the file at the current cursor position.
Writing Binary Files with "wb"
Binary mode writes raw bytes without any encoding or newline translation. It is required for images, audio, video, PDF files, serialized objects, and any format that is not plain text:
# Writing raw bytes
data = b'\x89PNG\r\n\x1a\n' # PNG file header
with open("image_copy.png", "wb") as f:
f.write(data)
Reading a binary file and writing a copy:
with open("original.jpg", "rb") as src:
with open("backup.jpg", "wb") as dst:
dst.write(src.read())
Do not specify encoding in binary mode — Python raises ValueError if you do. In binary mode, .write() accepts a bytes or bytearray object and returns the number of bytes written.
Chunked binary copy for large files avoids loading the entire file into memory:
CHUNK = 65536 # 64 KB
with open("large_video.mp4", "rb") as src:
with open("large_video_backup.mp4", "wb") as dst:
while chunk := src.read(CHUNK):
dst.write(chunk)
The walrus operator (:=, Python 3.8+) reads a chunk and assigns it in the same expression, terminating the loop when src.read() returns an empty bytes object.
Newline Handling and the newline Parameter
Python's text mode performs newline translation by default. On Windows, \n in your string is written as \r\n (CRLF) to disk. On Linux and macOS, \n is written as \n (LF). Reading a file on a different platform than it was written on can produce unexpected results.
The newline parameter controls this translation:
# Default — platform-specific translation
with open("output.txt", "w", encoding="utf-8") as f:
f.write("line one\nline two\n")
# newline="" — write exactly what you provide, no translation
with open("output.txt", "w", encoding="utf-8", newline="") as f:
f.write("line one\nline two\n")
# newline="\n" — forces LF on all platforms, even Windows
with open("output.txt", "w", encoding="utf-8", newline="\n") as f:
f.write("line one\nline two\n")
For most text files, the default behaviour is appropriate. The newline parameter becomes critical in two situations:
- CSV files: the
csvmodule requiresnewline=""when opening the file, because the module manages its own line endings and double-translation produces extra blank rows on Windows. - Cross-platform files: source code, configuration files, and logs that must have consistent LF endings regardless of the writing platform.
Writing CSV Files
The csv module handles quoting, escaping, and delimiter logic automatically. Always open the file with newline="" so the csv module controls line endings:
import csv
rows = [
["Name", "Age", "City"],
["Alice", 30, "Osaka"],
["Bob", 25, "Tokyo"],
["Charlie", 35, "Kyoto"],
]
with open("people.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
writer.writerows(rows)
writer.writerow(row) writes a single row. writer.writerows(rows) writes all rows in one call.
Writing CSV from a list of dictionaries using csv.DictWriter:
import csv
people = [
{"Name": "Alice", "Age": 30, "City": "Osaka"},
{"Name": "Bob", "Age": 25, "City": "Tokyo"},
]
fieldnames = ["Name", "Age", "City"]
with open("people.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(people)
DictWriter maps dictionary keys to column positions, making the code more robust to column reordering than a plain list approach.
Writing JSON Files
json.dump() serializes a Python object directly to an open file handle. It is more efficient than json.dumps() followed by .write() because it streams the output rather than building the entire JSON string in memory first:
import json
config = {
"server": "prod-01",
"port": 8080,
"debug": False,
"allowed_hosts": ["10.0.0.1", "10.0.0.2"],
}
with open("config.json", "w", encoding="utf-8") as f:
json.dump(config, f, indent=2)
The indent parameter controls pretty-printing. indent=2 or indent=4 produces human-readable output. Omitting indent produces compact single-line JSON, which is appropriate for machine-to-machine communication.
Additional json.dump() options:
with open("config.json", "w", encoding="utf-8") as f:
json.dump(config, f, indent=2, sort_keys=True, ensure_ascii=False)
sort_keys=True sorts dictionary keys alphabetically, producing deterministic output that is easier to diff in version control. ensure_ascii=False allows non-ASCII characters (Japanese, Arabic, accented characters) to appear as their actual Unicode characters rather than \uXXXX escape sequences.
Writing Files with pathlib
pathlib.Path provides a modern, object-oriented interface for file operations. Path.write_text() is a concise alternative to with open(...) for simple cases — it handles opening, writing, and closing in a single call:
from pathlib import Path
Path("output.txt").write_text("Hello, world!\n", encoding="utf-8")
For binary data, use Path.write_bytes():
Path("data.bin").write_bytes(b'\x00\x01\x02\x03')
Both methods always overwrite the file if it exists — there is no append or exclusive-create equivalent. When you need "a" or "x" behaviour with pathlib, open the file normally using Path.open():
path = Path("events.log")
with path.open("a", encoding="utf-8") as f:
f.write("New event\n")
Path objects also provide utility methods for constructing paths reliably across operating systems:
from pathlib import Path
output_dir = Path("results") / "2026" / "may"
output_dir.mkdir(parents=True, exist_ok=True) # Create directories if missing
output_file = output_dir / "report.txt"
output_file.write_text("Report content\n", encoding="utf-8")
Writing Large Files Efficiently
Loading a large dataset entirely into memory before writing is unnecessary and wasteful. Write data in chunks or line by line, letting the operating system's write buffer handle the I/O:
def generate_records(n):
for i in range(n):
yield f"record_{i:08d},value_{i}\n"
with open("large_output.csv", "w", encoding="utf-8") as f:
for line in generate_records(10_000_000):
f.write(line)
This writes 10 million records without holding more than one line in memory at a time. Python's internal write buffer (typically 8 KB) accumulates writes and flushes to disk in larger blocks automatically — you do not need to manage this manually.
Flushing the buffer manually — in scenarios where another process must see the data before the file is closed (log monitoring, real-time output), use f.flush():
import time
with open("live.log", "a", encoding="utf-8") as f:
for i in range(10):
f.write(f"Step {i} complete\n")
f.flush() # Write buffer to OS immediately
time.sleep(1)
Creating Directories Before Writing
open() does not create missing parent directories. Attempting to write to results/2026/report.txt when the results/2026/ directory does not exist raises FileNotFoundError:
from pathlib import Path
output_path = Path("results/2026/report.txt")
output_path.parent.mkdir(parents=True, exist_ok=True)
with open(output_path, "w", encoding="utf-8") as f:
f.write("Report content\n")
mkdir(parents=True, exist_ok=True) creates the full directory tree if it does not exist and raises no error if it already does. This is the production-correct pattern for writing to paths that may or may not already exist.
Writing to sys.stdout
sys.stdout is a writable file object. Any code that accepts a file handle and calls .write() on it can write to standard output instead of a file, with no changes to the writing logic:
import sys
def write_report(file_handle, data):
for key, value in data.items():
file_handle.write(f"{key}: {value}\n")
data = {"Server": "prod-01", "Status": "OK", "Uptime": "99.9%"}
# Write to a file
with open("report.txt", "w", encoding="utf-8") as f:
write_report(f, data)
# Write to stdout — same function, no changes
write_report(sys.stdout, data)
This pattern — writing to an abstract file handle rather than a hardcoded filename — makes functions testable, reusable, and composable without modification.
Error Handling
Three errors arise most commonly when writing files.
FileNotFoundError — the directory in the specified path does not exist:
try:
with open("missing_dir/output.txt", "w", encoding="utf-8") as f:
f.write("data")
except FileNotFoundError:
print("The target directory does not exist.")
PermissionError — the process does not have write permission for the location:
try:
with open("/etc/hosts", "w", encoding="utf-8") as f:
f.write("data")
except PermissionError:
print("Insufficient permissions to write to this location.")
FileExistsError — raised only in "x" mode when the file already exists:
try:
with open("output.txt", "x", encoding="utf-8") as f:
f.write("data")
except FileExistsError:
print("File already exists. Refusing to overwrite.")
OSError is the common base class for all file system errors, including disk-full conditions (errno.ENOSPC). In production code, catching OSError and inspecting e.errno gives precise control:
import errno
try:
with open("output.txt", "w", encoding="utf-8") as f:
f.write("data")
except OSError as e:
if e.errno == errno.ENOSPC:
print("Disk is full.")
elif e.errno == errno.EACCES:
print("Permission denied.")
else:
raise
Common Mistakes to Avoid
Opening in "w" mode when you meant "a". "w" truncates the file immediately. Every time your script runs, all previous content is gone. If you need to accumulate content across runs, use "a".
Forgetting \n in .write() calls. .write() writes exactly what you give it. Without \n, all your .write() calls produce a single continuous line in the file.
Forgetting newline="" when writing CSV. Without it, the csv module's internal \r\n handling combines with Python's default translation, producing \r\r\n on Windows and blank rows in the output.
Not specifying encoding. Files written without an explicit encoding on Windows may use cp1252, which cannot represent characters like €, ñ, or any CJK character, causing UnicodeEncodeError at runtime or silent data corruption.
Writing a massive string in one .write() call. Building a multi-GB string in memory and then writing it once is both slow and memory-inefficient. Write in a loop or using a generator.
Assuming .write() persists to disk immediately. Python buffers writes internally. If your process crashes after .write() but before .close(), data in the buffer is lost. Use f.flush() followed by os.fsync(f.fileno()) when durability is critical.
Modifying "r+" files without calling .truncate() after a shorter write. If the original file is 100 bytes and you write 60 bytes from position 0, the remaining 40 bytes of the original content are still in the file. Call f.truncate() after writing to remove the stale tail.
Writing Methods and Modes: Quick Reference
TaskModeMethodCreate or overwrite a text file"w"``.write() / .writelines()Append to a text file"a"``.write() / .writelines()Create a text file, fail if exists"x"``.write() / .writelines()Write binary data"wb"``.write(bytes)Append binary data"ab"``.write(bytes)Read and modify existing text file"r+"``.read(), .seek(), .write(), .truncate()Write then read back"w+"``.write(), .seek(0), .read()Write one-liner (small files)"w" via pathlibPath.write_text()Write binary one-liner"wb" via pathlibPath.write_bytes()Write CSV"w", newline=""``csv.writer / csv.DictWriterWrite JSON"w"``json.dump()
Best Practices Summary
- Always use
with open(...)— never rely on manual.close()calls - Always specify
encoding="utf-8"for all text file operations - Choose the mode before writing:
"w"to replace,"a"to append,"x"to create safely - Include
\nexplicitly in strings passed to.write()— it is never added automatically - Use
newline=""when opening files for thecsvmodule - Create parent directories with
Path.parent.mkdir(parents=True, exist_ok=True)before writing to nested paths - Write large files line by line or in chunks — avoid loading the entire output into memory
- Call
f.flush()when another process must see written data before the file is closed - Separate data generation from file writing — write functions that accept a file handle, not a filename
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Reading Files
Next
Working with JSON
-
File Modes for Writing
-
The
with open()Pattern — Always Use This -
Always Specify
encoding -
Writing Text with
.write() -
Writing Multiple Lines with
.writelines() -
Write Mode (
"w") — Overwrite an Existing File -
Append Mode (
"a") — Add to an Existing File -
Exclusive Creation Mode (
"x") — Safe File Creation -
Read-Write Modes:
"r+"and"w+".seek()and.tell()— Controlling Stream Position
-
Writing Binary Files with
"wb" -
Newline Handling and the
newlineParameter -
Writing CSV Files
-
Writing JSON Files
-
Writing Files with
pathlib -
Writing Large Files Efficiently
-
Creating Directories Before Writing
-
Writing to
sys.stdout -
Error Handling
-
Common Mistakes to Avoid
-
Writing Methods and Modes: Quick Reference
-
Best Practices Summary
