ZetCode

Python open 函数

上次修改时间:2025 年 4 月 11 日

本综合指南探讨了 Python 的 open 函数,该函数用于文件操作。我们将介绍文件模式、上下文管理器、编码以及读取和写入文件的实际示例。

基本定义

open 函数打开一个文件并返回一个文件对象。 它是 Python 中与文件交互的主要方式。 该函数将文件路径和模式作为参数。

主要特点:支持各种模式(读取、写入、追加、二进制)、处理文本和二进制数据、管理文件指针,并且应与上下文管理器一起使用以进行正确的资源清理。

读取文本文件

以下是如何使用最简单的 open 函数形式打开和读取文本文件。 此示例演示了基本的文件读取。

read_file.py
# Open file in read mode (default)
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

# Alternative line-by-line reading
with open('example.txt') as file:
    for line in file:
        print(line.strip())

此示例显示了读取文件的两种方法。 第一种一次读取整个内容。 第二种逐行读取,这对于大型文件来说在内存方面是高效的。

即使发生错误,with 语句也能确保正确关闭文件。 默认模式是“r”(读取),因此可以省略。

写入文件

此示例演示如何使用不同的写入模式将数据写入文件。 我们将介绍覆盖和追加。

write_file.py
# Write mode (overwrites existing file)
with open('output.txt', 'w') as file:
    file.write("Hello, World!\n")
    file.write("This is a new line.\n")

# Append mode (adds to existing file)
with open('output.txt', 'a') as file:
    file.write("This line is appended.\n")

第一个代码块使用“w”模式,该模式创建一个新文件或覆盖现有文件。 第二个代码块使用“a”模式附加到文件而不修改现有内容。

请注意,我们手动添加换行符 (\n),因为 write 不像 print 那样自动添加它们。

处理二进制文件

二进制模式用于非文本文件,如图像或可执行文件。 此示例显示了如何读取和写入二进制数据。

binary_file.py
# Copy an image file
with open('source.jpg', 'rb') as source:
    with open('copy.jpg', 'wb') as target:
        target.write(source.read())

# Working with binary data
with open('data.bin', 'wb') as file:
    file.write(b'\x00\x01\x02\x03\x04')

第一个示例通过以二进制模式读取和写入来复制图像文件。 第二个演示了如何将原始字节写入文件。

对于非文本文件,二进制模式 ('b') 至关重要,以防止 Python 修改行尾或尝试将内容解码为文本。

带编码的文件操作

在使用文本文件时,指定正确的编码至关重要。 此示例显示了如何处理不同的编码。

encoding.py
# Write with UTF-8 encoding
with open('utf8_file.txt', 'w', encoding='utf-8') as file:
    file.write("Some text with Unicode characters: ©®™\n")

# Read with specific encoding
with open('utf8_file.txt', 'r', encoding='utf-8') as file:
    print(file.read())

# Handling encoding errors
try:
    with open('utf8_file.txt', 'r', encoding='ascii') as file:
        print(file.read())
except UnicodeDecodeError as e:
    print(f"Encoding error: {e}")

第一个代码块使用 UTF-8 编码写入文件,该编码支持 Unicode 字符。 第二个代码块使用相同的编码将其读回。

第三个代码块演示了使用错误的编码时会发生什么,从而导致非 ASCII 字符出现 UnicodeDecodeError

高级文件操作

此示例显示了更高级的文件操作,包括查找、tell 和读取特定数量的数据。

advanced.py
with open('data.txt', 'w+') as file:
    # Write some data
    file.write("Line 1\nLine 2\nLine 3\n")
    
    # Move to beginning
    file.seek(0)
    
    # Read first 5 bytes
    print(file.read(5))  # "Line "
    
    # Get current position
    print(file.tell())   # 5
    
    # Read next line
    print(file.readline())  # "1\n"

这演示了文件指针操作。 seek 移动指针,tell 报告其位置,read(n) 读取特定数量的字节。

“w+”模式打开用于读取和写入(首先截断文件)。 类似的模式包括“r+”(读/写,不截断)和“a+”(追加/读)。

最佳实践

资料来源

作者

我的名字是 Jan Bodnar,我是一位充满热情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直撰写编程文章。 迄今为止,我已经撰写了 1,400 多篇文章和 8 本电子书。 我在编程教学方面拥有超过十年的经验。

列出所有 Python 教程