open() 是 Python 内置的用于打开文件的函数,它返回一个文件对象(file object),之后可以对该文件进行读取、写入等操作。open() 是 Python 中所有文件 I/O 的基础。
一、函数签名
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
参数说明
| |
|---|
file | |
mode | |
buffering | |
encoding | |
errors | |
newline | |
closefd | |
opener | |
二、打开模式(mode)详解
基本模式
扩展模式(可组合)
| | |
|---|
'+' | | 可与 r/w/a/x 组合,如 'r+', 'w+', 'a+' |
'b' | | |
't' | | |
常用模式组合
| |
|---|
'r' | |
'rb' | |
'w' | |
'wb' | |
'a' | |
'ab' | |
'r+' | |
'w+' | |
'a+' | |
'x' | |
三、返回值
open() 返回一个文件对象(file object),根据模式不同,可能是 io.TextIOWrapper(文本模式)或 io.BufferedReader/io.BufferedWriter(二进制模式)。文件对象提供以下常用方法:
读方法
写方法
定位方法
属性
closed – 文件是否关闭
mode – 打开模式
name – 文件名
其他
flush() – 刷新缓冲区
close() – 关闭文件
四、基本使用示例
1. 读取文本文件
# 方法1:read() 全部读取with open('data.txt', 'r', encoding='utf-8') as f: content = f.read() print(content)# 方法2:逐行读取(推荐大文件)with open('data.txt', 'r', encoding='utf-8') as f: for line in f: print(line, end='')# 方法3:readlines()with open('data.txt', 'r') as f: lines = f.readlines() for line in lines: print(line.strip())
2. 写入文本文件
# 覆盖写入with open('output.txt', 'w', encoding='utf-8') as f: f.write("第一行\n") f.write("第二行\n")# 追加写入with open('output.txt', 'a', encoding='utf-8') as f: f.write("追加的行\n")# 写入多行lines = ["行1\n", "行2\n", "行3\n"]with open('output.txt', 'w') as f: f.writelines(lines)
3. 读写二进制文件
# 复制图片with open('source.jpg', 'rb') as src: data = src.read()with open('copy.jpg', 'wb') as dst: dst.write(data)
4. 使用 r+ 读写模式
withopen('data.txt', 'r+', encoding='utf-8') as f: content = f.read() f.seek(0) # 回到开头 f.write("新内容\n" + content) # 在开头插入内容
五、编码处理
文本模式下强烈建议指定 encoding 参数,避免平台差异导致的乱码。
# 正确方式with open('file.txt', 'r', encoding='utf-8') as f: ...# 错误方式(不指定编码可能导致 Windows 上使用 GBK)with open('file.txt', 'r') as f: ...
常见编码
'utf-8' – 通用编码
'gbk' – Windows 简体中文
'latin-1' – 不抛出解码错误
'ascii' – 纯英文
errors 参数
| |
|---|
'strict' | |
'ignore' | |
'replace' | |
'backslashreplace' | |
'xmlcharrefreplace' | |
# 忽略错误withopen('file.txt', 'r', encoding='utf-8', errors='ignore') as f: content = f.read()
六、缓冲(buffering)
七、newline 参数(文本模式)
用于控制换行符的转换,跨平台时很有用。
| | |
|---|
None | \r | \n |
'' | | |
'\n' | \n | |
'\r' | \r | |
'\r\n' | \r\n | |
# 禁止换行符转换,保持原样with open('data.txt', 'r', newline='') as f: for line in f: print(repr(line)) # 会显示 \r\n 等
八、with 语句(上下文管理器)
with 语句确保文件在退出块时自动关闭,即使发生异常也不会泄漏资源。推荐总是使用 with。
# 不推荐(手动 close)f = open('test.txt', 'r')data = f.read()f.close()# 推荐(自动关闭)with open('test.txt', 'r') as f: data = f.read()# 块结束后文件已关闭
同时打开多个文件:
with open('src.txt', 'r') as src, open('dst.txt', 'w') as dst: dst.write(src.read())
九、异常处理
文件操作常见异常:
FileNotFoundError – 文件不存在(只读模式)
PermissionError – 权限不足
IsADirectoryError – 试图打开目录作为文件
UnicodeDecodeError – 编码解码错误
IOError / OSError – 底层 I/O 错误
示例:
try: with open('important.txt', 'r', encoding='utf-8') as f: data = f.read()except FileNotFoundError: print("文件不存在,创建默认配置") with open('important.txt', 'w') as f: f.write("default config")except PermissionError: print("没有读取权限")except UnicodeDecodeError: print("文件编码不是 UTF-8")
十、使用 pathlib 与 open() 结合
pathlib.Path 对象可以直接传给 open():
from pathlib import Pathp = Path('data') / 'info.txt'with open(p, 'r', encoding='utf-8') as f: content = f.read()
也可以使用 Path.open() 方法(效果相同):
with p.open('r', encoding='utf-8') as f: content = f.read()
十一、性能建议
大文件逐行处理:避免一次读入内存
指定合理编码:避免频繁解码错误
使用缓冲:通常默认值即可
二进制模式读写:对于非文本文件使用 'rb'/'wb'
十二、总结
| |
|---|
| 必须指定编码 | 文本模式建议显式 encoding='utf-8' |
| 使用 with 语句 | |
| 区分模式和文件类型 | |
| 处理异常 | 特别是 FileNotFoundError 和 PermissionError |
| 大文件处理 | 使用 for line in f: 而不是 read() |
open() 是 Python 文件操作的核心,掌握它的参数和行为能够帮助你高效、安全地处理各种文件 I/O 任务。