File Handling in Python
Opening and closing files
Open files in the right mode and close them safely.
To work with a file, a program first opens it:
file_object = open(file_name, access_mode)
open() returns a file object (also called a file handle), which the program then uses to read or write. A file object has attributes such as closed (True if the file is closed), mode (how it was opened) and name (the file's name).
The access mode says what the program will do with the file. Think of a cursor (the file pointer) marking where the next read or write will happen:
| Mode | Meaning | Cursor starts at |
|---|---|---|
| r | read only (the default); the file must already exist | beginning |
| r+ | read and write | beginning |
| w | write only; creates the file, or overwrites an existing one (old data is lost) | beginning |
| w+ | write and read; also overwrites | beginning |
| a | append: write at the end, keeping old data; creates the file if needed | end |
| a+ | append and read | end |
Files open in text mode by default. Adding b opens them in binary mode: rb, wb, ab, rb+, wb+ and so on.
When finished, the program should close the file with file_object.close(). Closing flushes (writes out) any data still waiting in memory, and frees the memory used.
A safer way is the with clause: with open(file_name, mode) as f: followed by the statements that use the file. The file is closed automatically when the block ends, even if an exception happens inside it.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.