Python 101Free
MODULES AND FILES

File I/O

Read from and write to files on disk.

SECTION 01

open and file modes

open(path, mode) returns a file object. The mode is a short string. r means read (the default), w means write (truncate the file or create it fresh), a means append (write at the end without overwriting). For text files, also pass encoding="utf-8"; without it Python guesses, and the guess can be wrong on Windows.

The file object is a resource. It holds an open handle and needs to be closed when you are done. The right way to handle this is to use open inside a with block. The with statement closes the file automatically when the block exits, including if an exception is raised in the middle.

Forget to close a file and you may run out of file descriptors, lose unwritten data, or hold a lock you do not need. The with form makes the issue impossible to forget.

python
with open("notes.txt", "a", encoding="utf-8") as f:
    f.write("new line\n")
# 'r' read (default), 'w' truncate, 'a' append
SECTION 02

Reading and writing

f.read() returns the whole file as a single string. f.readlines() returns a list of lines, including the newline characters. Both load the entire file into memory, which is fine for small files and bad for large ones.

The memory-friendly default is for line in f:. The file object is its own iterator, yielding one line per iteration. This is what to reach for when the file is big or the size is unknown.

For writing, f.write(s) writes a single string. f.writelines(lst) writes each element of a list. Neither adds newlines automatically; if you want them, include the newlines in the strings yourself.

python
with open("big.log") as f:
    for line in f:                # one line at a time
        if "error" in line:
            print(line, end="")

with open("out.txt", "w") as f:
    f.writelines(f"{i}\n" for i in range(3))
SECTION 03

pathlib basics

pathlib.Path is the modern, object-oriented path API. Path("data") creates a path. The / operator joins it with another segment: Path("data") / "input.txt" produces Path("data/input.txt"). The result is a Path object, not a string.

Methods on the path replace most os.path helpers. .exists() checks whether the path is on disk. .is_file() and .is_dir() distinguish kinds. .read_text() and .write_text(s) read and write the whole file in one call without ever managing a file handle.

Use pathlib for new code. The os.path functions still exist and still work, but they always operate on strings, which makes them more error-prone in cross-platform code.

python
from pathlib import Path

p = Path("data") / "input.txt"
p.exists()
p.is_file()
text = p.read_text(encoding="utf-8")
← PREVIOUS
Modules and Imports