Skip to content

File Handling in Python

读取 and 编写 files 使用打开(), 模式, 使用语句, and path 操作使用 pathlib.

你将学到

  • 打开 and 关闭 files 使用打开() and 关闭()
  • Use 使用语句 for automatic resource cleanup
  • 读取 and 编写文本 and binary files
  • Iterate over file 行 efficiently
  • 工作使用 paths using pathlib 模块

概念讲解

Opening Files

The built-in 打开() function opens a file and returns a file object. You must specify a mode:

f = open("数据.txt", "r")   # read (default)
f = open("数据.txt", "w")   # write (truncates file)
f = open("数据.txt", "")   # append
f = open("数据.txt", "rb")  # read binary

| Mode | Description | |------|-------------| | r | Read (default) — file must exist | | w | Write — creates or truncates | | ` | Append — creates or adds to end | | r+ | Read and write | | b` | Binary mode (add to above) |

Always close files when done: f.关闭(). However, the with statement is strongly preferred because it guarantees the file is closed even if an error occurs.

The with Statement

# BEST PRACTICE — file auto-closes even on error
with open("数据.txt", "r") as f:
    content = f.read()
# f is closed here automatically

The 使用 statement calls f.__enter__() on entry and f.__exit__() on exit, which handles closing. This is the only recommended way to work with files — never use bare 打开() without 使用 in production code.

Reading Files

# Read entire file as one string
with open("数据.txt") as f:
    content = f.read()

# Read all lines into a list
with open("数据.txt") as f:
    lines = f.readlines()

# Iterate line by line — memory efficient for large files
with open("数据.txt") as f:
    for line in f:
        print(line.strip())

Iterating line by line (for 行 in f) is the most memory-efficient way to process large files — it reads one line at a time instead of loading the entire file into memory.

Writing Files

# Write text
with open("输出.txt", "w") as f:
    f.write("Hello, 世界!\n")
    f.write("其次行\n")

# Write multiple lines at once
lines = ["行 1\n", "行 2\n", "行 3\n"]
with open("输出.txt", "w") as f:
    f.writelines(lines)

Note that .编写() does not add a newline automatically — you must include \n yourself. The "w" mode truncates the file; use "" to append without erasing.

Encoding

Always specify encoding for text files to avoid platform-dependent defaults:

with open("数据.txt", "r", encoding="utf-8") as f:
    content = f.read()

Without encoding="utf-8", Python uses the system default (often cp1252 on Windows), which can cause UnicodeDecodeError when reading files created on other systems.

pathlib — Modern Path Handling

The pathlib module provides an object-oriented way to work with paths that is cleaner than os.path:

from pathlib import Path

p = Path("数据") / "file.txt"   # platform-independent path joining
print(p.exists())               # check if file exists
print(p.suffix)                 # '.txt'
print(p.stem)                   # 'file'
print(p.parent)                 # 'data'

# Read with pathlib — opens and closes automatically
content = p.read_text(encoding="utf-8")
p.write_text("新内容", encoding="utf-8")

# List files in a directory
for child in Path(".").iterdir():
    print(child)

pathlib is the modern, recommended way to handle paths. It works across operating systems and eliminates the need for os.path.连接() string concatenation.

示例代码

              # Writing a file with the with statement
with open("output.txt", "w", encoding="utf-8") as f:
    f.write("Hello, World!\n")
    f.write("Second line\n")
    f.writelines(["line 3\n", "line 4\n"])

# Reading the entire file
with open("output.txt", "r", encoding="utf-8") as f:
    content = f.read()
print(content)

# Reading line by line — memory efficient
print("Lines:")
with open("output.txt", encoding="utf-8") as f:
    for line in f:
        print(f"  {line.strip()}")

# Appending to a file
with open("output.txt", "a", encoding="utf-8") as f:
    f.write("Appended line\n")

# pathlib for modern path handling
from pathlib import Path

p = Path("output.txt")
print(f"Exists: {p.exists()}")
print(f"Suffix: {p.suffix}")
print(f"Size: {p.stat().st_size} bytes")

# Read via pathlib
text = p.read_text(encoding="utf-8")
print(f"First 20 chars: {text[:20]}")
            

Shows 编写使用使用语句, 读取整个内容 and 行-通过-行, appending, and using pathlib for path inspection and 读取. 使用语句 ensures files 是总是关闭 properly.

动手试一试

  • JSON Formatter

    读取 and 编写 JSON files 是常见 file I/O 任务.

  • CSV 到 JSON

    CSV file 读取 and JSON conversion — practical file handling.

常见错误

错误写法

Forgetting 到关闭 files 当 using 打开() 不使用使用

正确做法

总是 use 使用语句: 使用打开('file') as f:. 它 automatically 关闭 file 偶数如果异常 occurs. 从不 rely on calling f.关闭() manually — 它能 是 skipped 如果错误 happens.

错误写法

不 specifying encoding='utf-8' 当读取文本 files

正确做法

不使用 explicit encoding, Python uses 系统默认哪个 varies 通过 platform. 这个 causes UnicodeDecodeError on files 从 other 系统. 总是通过 encoding='utf-8' for 文本 files.

相关速查表

练习 File Handling in Python

4 个练习

练习 File Handling in Python

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误