12. File Handling

File Handling

Programs often need to remember information after they stop running, or to read data someone else prepared. Files on disk make this possible. Python can create, read, and write text files with just a few lines of code.

Opening a file

The open() function connects your program to a file. You give it a file name and a mode that says what you intend to do. The mode is a short string.

ModeMeaningIf file exists
"r"Read (the default)Reads it; error if missing
"w"WriteErases and overwrites it
"a"AppendAdds to the end
"x"Create newError if it already exists

The with statement

The recommended way to work with a file is the with statement. It opens the file, gives you a variable to use inside the indented block, and automatically closes the file afterwards, even if an error occurs. Forgetting to close files is a classic bug that with prevents:

PYTHON
with open("notes.txt", "w") as f:
    f.write("First line\n")
    f.write("Second line\n")
print("File written.")
▸ OUTPUT
File written.

The \n is a newline character; without it, both pieces of text would run together on one line.

Reading a whole file

To read the file back, open it in read mode. The .read() method returns the entire contents as one string:

PYTHON
with open("notes.txt", "r") as f:
    content = f.read()
print(content)
▸ OUTPUT
First line
Second line

Reading line by line

For larger files it is better to process one line at a time. You can loop directly over the file object, which yields each line in turn, or use .readlines() to get a list of all lines:

PYTHON
with open("notes.txt", "r") as f:
    for line in f:
        print(line.strip())
▸ OUTPUT
First line
Second line

We call .strip() on each line to remove the trailing newline so print does not add a second blank line. .readlines() would instead give ['First line\n', 'Second line\n'].

Appending to a file

Open in append mode to add to a file without erasing what is already there:

PYTHON
with open("notes.txt", "a") as f:
    f.write("Third line\n")

with open("notes.txt", "r") as f:
    print(f.read())
▸ OUTPUT
First line
Second line
Third line

A note about CSV files

A very common file format is CSV (comma-separated values), used by spreadsheets. Each line is a row and commas separate the columns. You could split lines yourself, but Python's built-in csv module handles the tricky details for you:

PYTHON
import csv

with open("people.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["name", "age"])
    writer.writerow(["Ada", 25])

with open("people.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
▸ OUTPUT
['name', 'age']
['Ada', '25']

Notice that every value read from a CSV file comes back as a string, so you would convert row[1] with int() if you needed the age as a number.

With files, your programs can save results, keep logs, and read data prepared elsewhere. Always prefer the with statement so your files are closed safely, and be careful with "w" mode because it erases existing content.