Python Files — open, read, write, and with
Most useful programs read input from a file or save results to one. This guide shows the working core of Python file handling: the main write-then-read flow, the modes that decide whether a file is emptied, added to, or must not exist yet, the ways to read a file back, why the with statement is the safe way to open a file, the pathlib shortcut for whole-file text, and binary mode for data that is not text at all.
Written November 12, 2026 · Tested with Python 3.12.3 · 9 min read
- The main program: write, then read back
- Modes: write empties, append adds, x refuses
- Reading: all at once, one line, or line by line
- Why with closes the file, even on failure
Written November 12, 2026
Tested with Python 3.12.3
What this guide is
A file object connects your program to a file on disk. The open function creates it, and the mode argument says what you may do with it: read, write, or append. A text file moves strings and needs an encoding; a binary file moves bytes and needs none. The most important habit comes first in every example here: open the file in a with statement, so Python closes it for you when the block ends, on success and on failure. Everything else is choosing the right mode and the right way to read.
The main program: write, then read back
Opening with mode w creates the file if it does not exist and empties it if it does. Writing a string that ends in a newline writes a line. Opening again with mode r, which is also the default, reads the content back as one string:
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("first line\n")
f.write("second line\n")
with open("notes.txt", "r", encoding="utf-8") as f:
text = f.read()
print(repr(text))
print(text, end="")
print("lines:", len(text.splitlines()))
The exact output:
'first line\nsecond line\n'
first line
second line
lines: 2
The repr line shows what the file truly holds: two lines, each ending in the newline character. Printing the string shows the same content as lines. Two details carry into real work. First, write does not add newlines for you, so each line you want on its own line needs its own newline at the end. Second, naming encoding every time you open a text file makes the program behave the same on every machine, instead of depending on the system default, which differs between platforms.
Modes: write empties, append adds, x refuses
The mode letter is a promise about what happens to a file that already exists. Mode w empties it before writing. Mode a writes at the end and keeps what is there. Mode x creates a new file and fails if the name is already taken, which protects you from overwriting a result by accident:
with open("log.txt", "w", encoding="utf-8") as f:
f.write("start\n")
with open("log.txt", "a", encoding="utf-8") as f:
f.write("next\n")
with open("log.txt", encoding="utf-8") as f:
print(f.read(), end="")
try:
open("log.txt", "x")
except FileExistsError as e:
print(f"FileExistsError: {e}")
with open("log.txt", "w", encoding="utf-8") as f:
f.write("fresh\n")
with open("log.txt", encoding="utf-8") as f:
print(f.read(), end="")
The exact output:
start
next
FileExistsError: [Errno 17] File exists: 'log.txt'
fresh
Reading the file after the append shows both lines. The x open fails, because the file exists, and the error message names the file. Opening with w at the end replaces the whole content, so the last read shows only the fresh line. Pick the mode by the question you can answer before you open: should old content survive? If yes, append or read first. Should this run refuse to reuse a name? Then x gives you that refusal as an error you can report, rather than a silent overwrite you find out about later.
Reading: all at once, one line, or line by line
The read method returns everything from the current position to the end. The readline method returns one line, keeping its newline, and the next call continues where the last one stopped. Iterating the file object yields one line at a time, which reads a long file without holding all of it in memory at once:
with open("data.txt", "w", encoding="utf-8") as f:
f.write("alpha\nbeta\ngamma\n")
with open("data.txt", encoding="utf-8") as f:
print(repr(f.readline()))
print(repr(f.readline()))
print(repr(f.read()))
with open("data.txt", encoding="utf-8") as f:
for line in f:
print(line.strip().upper())
The exact output:
'alpha\n'
'beta\n'
'gamma\n'
ALPHA
BETA
GAMMA
Two readline calls consume the first two lines, so the read that follows returns only the third. Each line arrives with its newline attached, which is why repr shows the newline and why the loop strips it before printing. For a small file you know is small, read is the simple choice. For a log or a data file whose size you do not control, the loop is the safe choice, because only one line is in memory at a time.
Why with closes the file, even on failure
A file that stays open can lose buffered writes and can block other work on some systems. Closing by hand works, but it is easy to skip when an error interrupts the code between open and close. The with statement closes the file when the block ends, including when the block raises:
f = open("temp.txt", "w", encoding="utf-8")
f.write("x\n")
f.close()
print("after close:", f.closed)
try:
with open("temp.txt", encoding="utf-8") as g:
print("inside:", g.closed)
raise ValueError("boom")
except ValueError:
print("caught boom")
print("after with:", g.closed)
The exact output:
after close: True
inside: False
caught boom
after with: True
The closed attribute reports the state directly. Inside the with block the file is open. After the block, even though a ValueError ended it early, the file is closed. That guarantee is the reason with is the normal form for opening files: the close no longer depends on your code reaching a close line. The short open, write, and close at the top works, but it is the form to avoid for anything between open and close that could fail.
pathlib: whole-file text in one call
For short files, the pathlib module folds the open, read or write, and close into a single method call. A Path also splits a file name into parts, answers whether the file exists, and can delete the file:
from pathlib import Path
p = Path("report.txt")
p.write_text("one\ntwo\n", encoding="utf-8")
print(p.name, p.suffix, p.exists())
print(p.read_text(encoding="utf-8"), end="")
print("size:", p.stat().st_size)
p.unlink()
print("after unlink:", p.exists())
The exact output:
report.txt .txt True
one
two
size: 8
after unlink: False
The size is in bytes: two lines of three letters, each with a newline. The write_text and read_text methods take the same encoding argument as open, so the habit carries over. Reach for Path when the file is small and you want all of it at once. Reach for open and a loop when the file is large, when you read a line at a time, or when you write a piece at a time as results arrive.
Binary mode and the missing-file error
Adding b to the mode moves bytes instead of strings, and no encoding applies. Reading a binary file returns a bytes object, and turning it into a list shows the number stored in each byte. Binary mode suits images, archives, and any format whose bytes are not text. The same program shows the error for the opposite case, opening a text file that does not exist:
with open("data.bin", "wb") as f:
f.write(b"\x00\x01\x02")
with open("data.bin", "rb") as f:
data = f.read()
print(data)
print(list(data))
print(len(data))
try:
open("missing.txt", encoding="utf-8")
except FileNotFoundError as e:
print(f"FileNotFoundError: {e}")
The exact output:
b'\x00\x01\x02'
[0, 1, 2]
3
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'
Three bytes go in and the same three bytes come out, unchanged, because nothing decodes them. Opening a missing file for reading raises FileNotFoundError with the file name in the message. That error is the normal signal for a missing input: catch it when a missing file is a case your program can report and handle, and let it stop the program when the file was required and there is no useful way to continue.
Which form for which job
| Job | Form | Why |
|---|---|---|
| Create or replace a text file | open with w and an encoding | Old content is emptied on purpose |
| Add to a log or result file | open with a | New lines go after the existing content |
| Refuse to reuse a file name | open with x | An existing name raises FileExistsError |
| Read a small file whole | read, or Path read_text | One call returns the full string |
| Read a file of unknown size | Iterate the file object | One line in memory at a time |
| Continue reading in order | readline, then read | Each call picks up where the last stopped |
| Make sure a file closes | A with statement | The file closes on success and on error |
| Move non-text data | Add b to the mode | Bytes pass through with no decoding |
| React to a missing input | Catch FileNotFoundError | The message names the file that was not found |
Checklist
- Before opening a text file, name the encoding; the system default is not the same everywhere.
- Before opening with w, check whether the old content should survive; w empties the file at open, not at first write.
- Before reading a file whole, ask how large it can get; iterate when the size is not under your control.
- Before opening by hand and closing later, use with, so an error in between cannot leave the file open.
- Before writing data that is not text, switch to binary mode; decoding bytes as text corrupts them.
- Before treating a missing file as a crash, decide whether it is an expected case your program should report in its own words.
Related guides on this site
- Python Exceptions — try, except, else, finally, and raise — FileNotFoundError and FileExistsError are exceptions, and that guide shows how to handle them.
- Python Strings — Slicing, Methods, and f-Strings — a text file reads back as a string, and these are the methods that work on it.
- Python Functions — def, Default Arguments, and Functions as Values — reading and writing are usually wrapped in functions that take the file name as an argument.
- Python Classes and Objects — init, Methods, Inheritance, and Dataclasses — the with statement works through methods on the file object, the same mechanism classes define.
Sources
- Python Tutorial, Input and Output — reading and writing files, methods of file objects, and the with statement.
- Python Standard Library, Built-in Functions: open — the mode characters, encoding, and the exceptions open can raise.
- Python Standard Library, pathlib — Path, read_text, write_text, stat, and unlink.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.