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.


Related Items:readlines() close() open() read() int() list with

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 Yourself

Output:

TEXT 📖 Display only
# 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 Yourself

Output:

TEXT 📖 Display only
# Executed successfully

Tip: Always use with for 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 Yourself

Output:

TEXT 📖 Display only
First line
Second line
Third line


4. Ways to Read Files

▶ Example: Three Ways to Read a File

▶ Try it Yourself

Output:

TEXT 📖 Display only
# Executed successfully

▶ Example: File Backup Tool (Difficulty: Star-Star)

▶ Try it Yourself

Output:

TEXT 📖 Display only
# 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 Yourself

Output:

TEXT 📖 Display only
['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 Yourself

Output:

TEXT 📖 Display only
# 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 Yourself

Output:

TEXT 📖 Display only
# Executed successfully

▶ Example: pathlib Path Operations

▶ Try it Yourself

Output:

TEXT 📖 Display only
# Executed successfully

Tip: pathlib is the recommended way to handle paths in Python 3.4+. It's more object-oriented and intuitive than os.path. For new projects, use pathlib.



7. Common Use Cases


Related Items:readlines() close() open() read() int() list with

❓ FAQ

Q Do I always need to write encoding="utf-8"?
A In Chinese-language environments, it is strongly recommended every time. Python's default encoding varies by OS — Windows uses 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.
Q The "w" mode clears existing file content. How do I avoid accidental overwrites?
A Use "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.
Q How do I read very large files (hundreds of MB)?
A Don't use 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


📝 Exercises

  1. Beginner (Difficulty: Star): Write a program that accepts a user's name and age and saves them to a users.txt file (one user per line, format: name,age). Append new records each run without overwriting existing data.

  2. Intermediate (Difficulty: Star-Star): Write a program that reads the users.txt file from the previous exercise, parses each line, calculates and outputs the average age of users. Hint: Use split(",") to parse, int() to convert age.

  3. Advanced (Difficulty: Star-Star-Star): Write a "simple notebook" program. Features: add:title|content to add a note (append to notes.csv), list to list all notes, search:keyword to search notes. Store in CSV format (fields: title, content, creation time). Hint: Use datetime.now() for the current timestamp.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏