Skip to chapter content
navan✳THE BUILD LABPYTHON / GUIDE
0/26 read
CHAPTER 10 / 26 · FILES AND PROGRAMS

Reading and writing files.

Move between bytes on disk and values in memory with explicit paths and encodings.

BY NAVAN SAMI5 MIN READTHEORY FIRST
01 / THE BASICS

Start here.

Variables disappear when a program ends, but files keep data on a storage device. A path tells the operating system where a file is. pathlib.Path represents a path as an object with useful operations instead of forcing you to combine pieces of a filename as plain text. Path('notes.txt') is relative to the program's current working directory. It does not automatically mean the directory containing the Python source file.

Text files contain bytes that must be decoded into characters when read and encoded into bytes when written. UTF-8 is a common choice, so path.write_text(text, encoding='utf-8') makes that choice explicit. write_text creates or replaces a file; replacing existing content is a real effect, not merely a display in the terminal. Reading a whole file with read_text is simple for small files. Iterating over an open file yields one line at a time and uses less memory for large files.

Opening a file creates a handle, a resource the program should close. A with block closes it automatically when the block ends, including when an error occurs. The read mode 'r' reads, 'w' writes from the beginning and truncates an existing file, 'a' appends, and 'x' refuses to replace an existing file. The example prints each line after strip removes surrounding whitespace. That is appropriate for display, but a program preserving exact text may need to remove only the line ending.

02 / THE IDEA

Build the model.

A file gives data a life beyond one program run. A path identifies where it lives; opening it creates a file handle through which Python reads or writes. Text files require an encoding to turn bytes into characters. Use pathlib.Path for clear path operations and open files with a with block so the handle closes even if an error interrupts the work.

Reading the entire file is convenient for small inputs. For a large log, iterate over the file one line at a time to avoid holding the whole thing in memory. When writing, decide whether to replace an old file or append to it, and think about what should happen if the program stops halfway through.

03 / UNDER THE SURFACE

How it works.

Path('notes.txt') is relative to the process's current working directory, not necessarily the script's folder. Print Path.cwd() while debugging a missing file. Use an absolute or explicitly constructed path when the program may be launched from different places. Check whether parent directories exist before writing, but do not assume a check prevents another process from changing them afterward.

with path.open('r', encoding='utf-8') as handle gives you a text stream. The mode 'w' truncates an existing file; 'a' appends; 'x' fails if the file already exists. For binary data such as an image, use 'rb' or 'wb' and work with bytes. Treat errors such as FileNotFoundError and PermissionError as different situations with different recovery paths.

04 / A WORKED EXAMPLE

Read it line by line.

example.py
from pathlib import Path
path = Path('notes.txt')
path.write_text('one\ntwo\n', encoding='utf-8')
with path.open(encoding='utf-8') as handle:
    for line in handle:
        print(line.strip())

write_text creates or replaces notes.txt with two newline-terminated lines. The with block opens it for reading and closes it afterward. The loop receives each line including its newline. strip removes surrounding whitespace for display, so print outputs one and then two.

05 / ANOTHER EXAMPLE

See the rule again.

example-2.py
from pathlib import Path
path = Path('notes.txt')
with path.open(encoding='utf-8') as handle:
    count = sum(1 for line in handle if line.strip())
print(count)

The generator produces one for each nonblank line while the file is streamed. sum counts them. This is suitable for a large text file because it does not store all lines at once. The file closes when the with block ends.

06 / REMEMBER THIS

A mistake to avoid.

Do not apply strip to data when leading or trailing spaces are meaningful. To remove only the line ending, use rstrip('\n') and account for Windows-style carriage returns when necessary.

Finished this chapter?
Built with curiosity. By Navan Sami. ↗Python · Understand the idea, then write the code.