Python: File Input/Output Operations
Last updated: 2026-09-22
So far, our program data has only existed in memory — close the program, and the data is lost. File I/O allows programs to save data to disk and read it back on the next startup. This is a fundamental capability for any practical application.
1. Opening and Closing Files
The basic file operation has three steps: open -> read/write -> close.
▶ Example: Manually Opening and Closing a File
▶ Try it YourselfOutput:
# Executed successfully
Warning: Always remember
close()! Open files consume system resources. Forgetting to close can lead to file corruption or resource exhaustion. But don't worry — the next section has a better approach.
2. The with Statement (Context Manager)
The with statement automatically closes the file at the end of the code block, without needing to call close():
▶ Example: Safe File I/O with with
▶ Try it YourselfOutput:
# Executed successfully
Tip: Always use
withfor file operations. It's the safest, most Pythonic way — the file is correctly closed whether or not an exception occurs in the code block.
3. File Open Modes
The second parameter of open() is the mode:
| Mode | Meaning | File Exists | File Doesn't Exist |
|---|---|---|---|
"r" |
Read (default) | Read normally | Error |
"w" |
Write | Clear then write | Create |
"a" |
Append | Append to end | Create |
"x" |
Exclusive create | Error | Create |
"r+" |
Read and write | Readable and writable | Error |
▶ Example: Different File Open Modes
▶ Try it YourselfOutput:
First line
Second line
Third line
4. Ways to Read Files
▶ Example: Three Ways to Read a File
▶ Try it YourselfOutput:
# Executed successfully
▶ Example: File Backup Tool (Difficulty: Star-Star)
▶ Try it YourselfOutput:
# Function defined successfully
5. Reading and Writing CSV Files
CSV (Comma-Separated Values) is the most common data exchange format. Python has a built-in csv module:
▶ Example: CSV File I/O
▶ Try it YourselfOutput:
['Name', 'Age', 'City']
['Zhang San', '25', 'Beijing']
['Li Si', '30', 'Shanghai']
['Wang Wu', '22', 'Guangzhou']
(1) Using DictReader/DictWriter (More Intuitive)
▶ Example: DictReader/DictWriter for CSV
▶ Try it YourselfOutput:
# Executed successfully
6. Path Handling
Use os.path or pathlib for file path handling — safer than string concatenation:
▶ Example: os.path Path Handling
▶ Try it YourselfOutput:
# Executed successfully
(1) Recommended: pathlib (Python 3.4+)
▶ Example: pathlib Path Operations
▶ Try it YourselfOutput:
# Executed successfully
Tip:
pathlibis the recommended way to handle paths in Python 3.4+. It's more object-oriented and intuitive thanos.path. For new projects, usepathlib.
7. Common Use Cases
- Data persistence: Save program data to files, restore on next startup.
- Logging: Append program runtime information to log files.
- Configuration management: Read configuration files (
.ini,.json,.env). - Data import/export: Exchange data with Excel/databases using CSV format.
- Batch file processing: Traverse directories, batch modify file content or rename files.
❓ FAQ
encoding="utf-8"?gbk, macOS/Linux uses utf-8. Without specifying, processing Chinese text files on Windows may result in garbled output. Make it a habit to specify encoding for cross-platform peace of mind."w" mode clears existing file content. How do I avoid accidental overwrites?"x" mode (exclusive creation) — if the file already exists, it raises an error instead of clearing it. Or use os.path.exists() to check first. Data is precious — think twice before writing to a file.read() or readlines() — they load the entire file into memory. Use for line in file: to read line by line, processing only one line at a time with minimal memory usage. Alternatively, use read(1024) to read a specific number of bytes at a time.📖 Summary
- File operations in three steps:
open()-> read/write ->close() - The
withstatement manages file closure automatically — the safest approach - Modes:
"r"read,"w"write,"a"append - Reading methods:
read()full content,readlines()as list,for line in fline by line - The
csvmodule for CSV file I/O; supportsDictReader/DictWriter os.pathandpathlibfor file path handling;pathlibis more modern- Always specify
encoding="utf-8"for Chinese text file operations
📝 Exercises
-
Beginner (Difficulty: Star): Write a program that accepts a user's name and age and saves them to a
users.txtfile (one user per line, format:name,age). Append new records each run without overwriting existing data. -
Intermediate (Difficulty: Star-Star): Write a program that reads the
users.txtfile from the previous exercise, parses each line, calculates and outputs the average age of users. Hint: Usesplit(",")to parse,int()to convert age. -
Advanced (Difficulty: Star-Star-Star): Write a "simple notebook" program. Features:
add:title|contentto add a note (append tonotes.csv),listto list all notes,search:keywordto search notes. Store in CSV format (fields: title, content, creation time). Hint: Usedatetime.now()for the current timestamp.