fuckingpython.lol

Learn Python › Lesson 11

Python files: read them, write them, don't fucking wipe them

Updated · every example run on Python 3.9 to 3.15

Everything your programs have done so far evaporates the second they end. The shopping list, the cat's weight, the bank balance: gone, like a dream you were sure was important. A file is how a program remembers. You open it, read or write some text, and close it. Python makes this almost boring, which is the highest compliment a file API can get.

From here on, an example can come with more than one file. A box labeled shopping.txt is a file that sits next to main.py in the same folder. Make it in your editor with exactly that name, then run python3 main.py from that folder.

Read a whole file

open takes a file name and hands you a file object. with keeps it open for the indented block and closes it when the block ends, even if something inside blows up. f.read() gives you the entire file as one string.

shopping.txt
eggs
coffee
more coffee
main.py
with open("shopping.txt", encoding="utf-8") as f:
    text = f.read()

print(text)
print(len(text), "characters")
Python 3.9 to 3.15 all print
eggs
coffee
more coffee

24 characters

Count them yourself: 21 letters and spaces, plus three newlines, one at the end of each line. A newline is a character like any other, written \n. That blank line before the count is the file's last newline plus the one print adds. Nothing is broken; Python is just being literal as hell, as usual.

With no mode, open reads text. The encoding="utf-8" part gets its own section below. Type it every time anyway.

Loop over the lines

Most files are a list of things, one per line, so you usually want them one line at a time. There are two ways to get that:

todo.txt
feed the cat
pay rent
learn Python
main.py
with open("todo.txt", encoding="utf-8") as f:
    lines = f.readlines()
print(lines)

with open("todo.txt", encoding="utf-8") as f:
    for number, line in enumerate(f, start=1):
        print(number, line.strip())
Python 3.9 to 3.15 all print
['feed the cat\n', 'pay rent\n', 'learn Python\n']
1 feed the cat
2 pay rent
3 learn Python

readlines() returns a list of strings, and every one of them still carries its \n. It's an ordinary list, so lines[0] is the first line, and lines[3] on this three-line file is an IndexError. Looping straight over the file object gives you the same lines one at a time, so Python never holds the whole file in memory. For a 2 GB log file, that is the difference between working and your laptop fan achieving liftoff.

.strip() removes the newline (and any spaces or tabs at either end). Forget it and print(line) prints the line's newline and then one of its own, so your output comes out double-spaced like an essay padded to hit the page count. And strip the lines, not the list: lines.strip() gets you AttributeError: 'list' object has no attribute 'strip'. If you want a list without the newlines, f.read().splitlines() does it in one go.

Write and append

To write, open the file with a second argument, the mode. "w" means write, "a" means append:

main.py
with open("diary.txt", "w", encoding="utf-8") as f:
    f.write("Monday: started learning Python.\n")
    f.write("Tuesday: Python started learning me.\n")

with open("diary.txt", "a", encoding="utf-8") as f:
    f.write("Wednesday: wrote to a file.\n")

with open("diary.txt", encoding="utf-8") as f:
    print(f.read())

with open("diary.txt", "w", encoding="utf-8") as f:
    f.write("Thursday: opened it with w again.\n")

with open("diary.txt", encoding="utf-8") as f:
    print(f.read())
Python 3.9 to 3.15 all print
Monday: started learning Python.
Tuesday: Python started learning me.
Wednesday: wrote to a file.

Thursday: opened it with w again.

Look at what happened to Monday, Tuesday and Wednesday. "w" creates the file if it doesn't exist and empties it if it does, at the moment open runs, before you write a single character. No trash can, no undo, no "are you sure?". It is a fucking paper shredder with a friendly one-letter name. "a" keeps what is there and adds to the end, and it also creates the file if it's missing. Use "w" only when you mean to replace the whole file.

Two more things write does not do for you. It adds no newline, so the \n is your job. And it takes only strings: f.write(42) is a TypeError, so convert first with str(42) or an f-string.

Always say encoding="utf-8"

A file on disk is bytes. Text is characters. The encoding is the table that turns one into the other, and if the writer and the reader use different tables, you get garbage:

main.py
with open("menu.txt", "w", encoding="utf-8") as f:
    f.write("Café crème: $4\n")

with open("menu.txt", encoding="utf-8") as f:
    print(f.read().strip())

with open("menu.txt", encoding="cp1252") as f:
    print(f.read().strip())
Python 3.9 to 3.15 all print
Café crème: $4
Café crème: $4

The last read decodes on purpose with cp1252, an old Windows table. In UTF-8 an é takes two bytes, and cp1252 reads those two bytes as two separate characters. That mess has a name, mojibake, and it is what non-English text looks like after a trip through the wrong default.

And the default really did differ. Without encoding, Python up to 3.14 uses your system's locale encoding: UTF-8 on most Macs and Linux machines, often cp1252 or a similar code page on Windows. The same script could write a file fine on one laptop and mangle it on another. Python 3.15 finally made UTF-8 the damn default everywhere (PEP 686), but your code will meet older Pythons for years, so write encoding="utf-8" and stop thinking about it.

When the file isn't there

Now ask for a file that doesn't exist. Note the typo:

main.py
with open("shoping.txt", encoding="utf-8") as f:
    print(f.read())
Python 3.15 prints
Traceback (most recent call last):
  File "/home/me/project/main.py", line 1, in <module>
    with open("shoping.txt", encoding="utf-8") as f:
         ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'shoping.txt'
PythonPrints
3.9–3.15FileNotFoundError: [Errno 2] No such file or directory: 'shoping.txt'

Run on CPython 3.9.6, 3.10.22, 3.11.17, 3.12.15, 3.13.17, 3.14.9 and 3.15.1, on November 11, 2026.

FileNotFoundError is exactly what it says, in the same words on every version; from 3.11 on, Python also underlines the call that failed. The [Errno 2] is the operating system's own number for "no such file", passed along. The message quotes the name you asked for, so check it letter by letter: here the cat walked across the keyboard and took a "p" with it.

The other classic cause: a plain name like "shopping.txt" is looked up in the folder your terminal is in, not the folder main.py lives in. Run python3 code/main.py from one level up and Python looks for the file one level up. cd into the script's folder first.

Sometimes a missing file is normal, like the very first run of a program that keeps a list. Catch the error, as in lesson 10, and start empty:

try:
    with open("shopping.txt", encoding="utf-8") as f:
        items = f.read().splitlines()
except FileNotFoundError:
    items = []

pathlib: paths without the string glue

Gluing file names together with + means minding every slash yourself, and Windows writes its paths with \ where everyone else uses /. The pathlib module in Python's standard library has a Path type that knows the rules. The first line below brings it into your program; lesson 12 explains import properly.

main.py
from pathlib import Path

folder = Path("notes")
folder.mkdir(exist_ok=True)

shopping = folder / "shopping.txt"
shopping.write_text("eggs\ncoffee\n", encoding="utf-8")
(folder / "todo.txt").write_text("pay rent\n", encoding="utf-8")

print(shopping)
print(shopping.name, shopping.stem, shopping.suffix)
print(shopping.exists(), (folder / "nope.txt").exists())
print(shopping.read_text(encoding="utf-8").splitlines())
print(sorted(p.name for p in folder.glob("*.txt")))
Python 3.9 to 3.15 all print
notes/shopping.txt
shopping.txt shopping .txt
True False
['eggs', 'coffee']
['shopping.txt', 'todo.txt']

The / between a Path and a string joins them with the right separator for your system. On a Mac or Linux it prints notes/shopping.txt; on Windows, the same code prints a backslash. mkdir(exist_ok=True) makes the folder and stays quiet if it's already there. write_text and read_text open, write or read, and close in one call, no with needed. .name, .stem and .suffix pick a path apart, .exists() asks before you trip, and glob("*.txt") finds every matching file. The order glob returns them in depends on the file system, so sort it when the order matters.

Try it yourself

You log your daily steps in a file called steps.txt, one number per line. The file ends with an empty line, because somebody pressed Enter one extra time (it was you):

4200
8100
12050

Write a program that prints the total. Calling int() on that empty line gives you ValueError: invalid literal for int() with base 10, so skip it.

Show the answer
total = 0
with open("steps.txt", encoding="utf-8") as f:
    for line in f:
        line = line.strip()
        if line:
            total += int(line)
print("Total steps:", total)

An empty string is falsy, so if line: skips the blank line. It prints Total steps: 24350.

Questions

How do I read a file line by line in Python?

Open it with with open("name.txt", encoding="utf-8") as f: and loop with for line in f:. Each line keeps its newline at the end; line.strip() removes it.

What is the difference between w and a in Python's open()?

"w" empties the file the moment it opens it, then writes from the start. "a" keeps the contents and writes at the end. Both create the file if it doesn't exist yet.

Do I need to close a file if I use with?

No. The with block closes the file when it ends, even when an exception is raised inside it. Without with, you have to call f.close() yourself, and text you wrote may not reach the disk until you do.

Why do I get FileNotFoundError when the file is right there?

Because "right there" means next to the script, and Python looks next to the terminal. A relative name is looked up from the current working directory. Run the script from its own folder, or build the path from the script's location with Path(__file__).parent / "name.txt".

Sources

Read on November 11, 2026.