Python: File I/O

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

PYTHON
# Write to a file
file = open("hello.txt", "w", encoding="utf-8")
file.write("Hello, World!")
file.close()

# Read from a file
file = open("hello.txt", "r", encoding="utf-8")
content = file.read()
file.close()

print(content)              # Hello, World!
▶ 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

PYTHON
# Write
with open("hello.txt", "w", encoding="utf-8") as f:
    f.write("Hello, World!")

# Read
with open("hello.txt", "r", encoding="utf-8") as f:
    content = f.read()

print(content)
▶ 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

PYTHON
# "w" — write (clear and rewrite)
with open("test.txt", "w", encoding="utf-8") as f:
    f.write("First line\n")
    f.write("Second line\n")

# "a" — append
with open("test.txt", "a", encoding="utf-8") as f:
    f.write("Third line\n")

# "r" — read
with open("test.txt", "r", encoding="utf-8") as f:
    print(f.read())
▶ 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

PYTHON
# Assume file content:
# First line
# Second line
# Third line

# Method 1: read() — read all at once
with open("test.txt", "r", encoding="utf-8") as f:
    content = f.read()
print(content)

# Method 2: readlines() — read as a list
with open("test.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
print(lines)                # ['First line\n', 'Second line\n', 'Third line\n']

# Method 3: line by line (recommended)
with open("test.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())  # strip() removes newline characters
▶ Try it Yourself

Output:

TEXT 📖 Display only
# Executed successfully

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

PYTHON
def backup_file(filename):
    """Create a backup copy of a file"""
    try:
        with open(filename, "r", encoding="utf-8") as f:
            content = f.read()
        
        backup_name = filename + ".bak"
        with open(backup_name, "w", encoding="utf-8") as f:
            f.write(content)
        
        print(f"Backup created: {backup_name}")
    except FileNotFoundError:
        print(f"File {filename} does not exist!")

backup_file("test.txt")
▶ 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

PYTHON
import csv

# Write CSV
data = [
    ["Name", "Age", "City"],
    ["Zhang San", 25, "Beijing"],
    ["Li Si", 30, "Shanghai"],
    ["Wang Wu", 22, "Guangzhou"],
]

with open("students.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerows(data)

# Read CSV
with open("students.csv", "r", encoding="utf-8") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
▶ 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

PYTHON
import csv

# Write
data = [
    {"name": "Zhang San", "age": 25, "city": "Beijing"},
    {"name": "Li Si", "age": 30, "city": "Shanghai"},
]

with open("students_dict.csv", "w", newline="", encoding="utf-8") as f:
    fieldnames = ["name", "age", "city"]
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()       # Write header
    writer.writerows(data)     # Write data rows

# Read
with open("students_dict.csv", "r", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(f"{row['name']} — {row['age']} years old, from {row['city']}")
▶ 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

PYTHON
import os

# Get current directory
print(os.getcwd())          # /project

# Join paths (automatically handles separators)
path = os.path.join("data", "files", "test.txt")
print(path)                 # data/files/test.txt

# Check if path exists
print(os.path.exists("test.txt"))          # True/False
print(os.path.isfile("test.txt"))          # Is it a file?
print(os.path.isdir("data"))               # Is it a directory?

# Get file info
print(os.path.getsize("test.txt"))         # File size in bytes

# List directory contents
for f in os.listdir("."):
    print(f)
▶ Try it Yourself

Output:

TEXT 📖 Display only
# Executed successfully

▶ Example: pathlib Path Operations

PYTHON
from pathlib import Path

# Create a path
p = Path("data/files/test.txt")

# Path info
print(p.name)               # test.txt (filename)
print(p.stem)               # test (without extension)
print(p.suffix)             # .txt (extension)
print(p.parent)             # data/files (parent directory)

# Read/write file (concise)
p = Path("hello.txt")
p.write_text("Hello, World!", encoding="utf-8")
content = p.read_text(encoding="utf-8")
print(content)              # Hello, World!

# Recursive traversal
for py_file in Path(".").rglob("*.py"):
    print(py_file)
▶ 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


❓ 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%

🙏 帮我们做得更好

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

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