Files and with

Opening a file so it always closes, reading it a line at a time, and the modes that truncate what was there.

files.py

files.py Python 3
Output

                    

file_modes.py

file_modes.py Python 3
Output

                    

Worth knowing

with closes the file when the block ends, including when it raises.
"w" truncates the file immediately. "a" appends.
Iterating the file object reads one line at a time - the right way for large files.
Lines keep their trailing newline. Use .rstrip().

Files and with: A Practical Guide

Opening a file gives you an object to read or write. The with statement makes sure it is closed afterwards, which is the part that is easy to skip and expensive to get wrong.

A note about this page

These editors run Python in your browser against an in-memory filesystem. The files are real while the program runs and vanish afterwards, so everything below behaves exactly as it would on your machine — it just does not persist.

with, and why

with open("notes.txt") as f:
    content = f.read()

When the block ends the file is closed, whether it ended normally or by raising. Doing it by hand means f.close() in a finally, and forgetting it leaves the handle open — which on a long-running program eventually exhausts the operating system's limit, and on a write leaves data sitting in a buffer that never reaches the disk.

with is not a style preference here. It is the correct way to open a file.

Three ways to read

f.read()       # the whole thing as one string
f.readlines()  # a list of lines
for line in f: # one line at a time

The third is the one to reach for by default. It holds a single line in memory regardless of file size, so it works on a file larger than your RAM, and it reads no worse than the others.

Lines keep their trailing \n, which is why line.rstrip() appears in almost every loop over a file.

The modes

"r"  read, the default — raises if the file is missing
"w"  write — truncates immediately
"a"  append — writes to the end
"x"  create — raises if it already exists

"w" is the dangerous one. It empties the file the moment it is opened, before you write anything, so an open(path, "w") that then raises leaves you with nothing. When you mean "add to this", "a" is the mode.

"x" is worth remembering when overwriting would be a bug: it refuses rather than destroying.

Missing files raise

open("nope.txt") raises FileNotFoundError, it does not return an empty file. Handle it, or let it propagate — both are reasonable, but do not check with os.path.exists first: the file can disappear between the check and the open, and the try handles that correctly anyway.

Text and encoding

Files open in text mode and decode using your platform's default encoding, which differs between machines. For anything portable, say what you mean: open(path, encoding="utf-8").

Check yourself

0 of 3

Answer without scrolling back up.

  1. What does `with` do for a file?

  2. Opening an existing file with mode "w" does what?

  3. Why iterate `for line in f` rather than use readlines()?

Cheat sheet

Files and with

Opening a file gives you an object to read or write. The with statement makes sure it is closed afterwards, which is the part that is easy to skip and expensive to get wrong.

PYTHON · vizlearn.in/python/files_and_with.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.