Part 3: Python Programming
Part 3: Python Programming — read through each chapter in order. Diagrams, tables and worked examples included.
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.
| Mode | Meaning | If file exists |
|---|---|---|
"r" | Read (the default) | Reads it; error if missing |
"w" | Write | Erases and overwrites it |
"a" | Append | Adds to the end |
"x" | Create new | Error 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:
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:
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:
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:
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:
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.