read() 是 Python 文件对象的方法,用于从文件中读取指定数量的字节(二进制模式)或字符(文本模式)。如果不指定大小,则读取整个文件。
一、函数签名
参数说明
| |
|---|
size | 可选,要读取的字节数(二进制模式)或字符数(文本模式)。默认 -1 或省略表示读取所有剩余内容。 |
返回值
二、基本用法
1. 读取整个文件(小文件推荐)
with open('data.txt', 'r', encoding='utf-8') as f: content = f.read() # 读取全部内容 print(content)
2. 读取指定字符数(文本模式)
withopen('data.txt', 'r', encoding='utf-8') as f: first_10 = f.read(10) # 读取前10个字符 next_20 = f.read(20) # 接着读20个字符 rest = f.read() # 读取剩余部分
3. 读取指定字节数(二进制模式)
with open('image.jpg', 'rb') as f: header = f.read(100) # 读取前100字节 print(f"文件头前10字节: {header[:10]}")
4. 读取大文件分块处理
def process_large_file(file_path, chunk_size=8192): """分块读取大文件,避免内存溢出""" with open(file_path, 'rb') as f: while True: chunk = f.read(chunk_size) if not chunk: break # 处理每个块 process_chunk(chunk)
三、read() 与其他读取方法对比
| | | |
|---|
read() | | | |
readline() | | | |
readlines() | | | |
示例对比
# read() - 整体读取withopen('data.txt', 'r') as f: content = f.read() # 一次性读入内存# readline() - 逐行读取withopen('data.txt', 'r') as f: line = f.readline() while line: process(line) line = f.readline()# readlines() - 读取所有行withopen('data.txt', 'r') as f: lines = f.readlines() # 列表形式,占用内存
四、read() 的细节与注意事项
1. 文件指针移动
每次调用 read() 都会向前移动文件指针。tell() 可以查看当前位置。
with open('test.txt', 'r') as f: print(f.tell()) # 0 f.read(5) print(f.tell()) # 5 f.read() print(f.tell()) # 文件总大小
2. 读取到文件末尾
当 read() 返回空字符串(文本)或空字节串(二进制)时,表示已到 EOF。
with open('data.txt', 'r') as f: while True: data = f.read(1024) if not data: # 空字符串表示结束 break process(data)
3. 编码问题(文本模式)
4. 二进制模式
不进行任何编码转换,直接读取原始字节。
适合图片、视频、压缩包等非文本文件。
withopen('data.bin', 'rb') as f: first_byte = f.read(1) # b'\x00'
5. 性能考虑
对于小文件(几 MB),一次性 read() 简单高效。
对于超大文件(几百 MB 或 GB),应分块读取避免内存耗尽。
块大小通常为 4KB、8KB 或 1MB,取决于磁盘和系统。
五、实际应用场景
1. 复制文件(分块复制)
def copy_file(src, dst, chunk_size=8192): with open(src, 'rb') as f_src: with open(dst, 'wb') as f_dst: while True: chunk = f_src.read(chunk_size) if not chunk: break f_dst.write(chunk)
2. 读取文件头判断类型
def get_file_type(file_path): with open(file_path, 'rb') as f: header = f.read(4) if header.startswith(b'\x89PNG'): return 'PNG' elif header.startswith(b'%PDF'): return 'PDF' elif header.startswith(b'GIF8'): return 'GIF' else: return 'Unknown'
3. 读取配置文件(一次性加载)
def load_config(file_path): try: with open(file_path, 'r', encoding='utf-8') as f: return json.loads(f.read()) except FileNotFoundError: return {}
六、read() 与 readline() 的配合
有时需要先读取一行判断,然后读取剩余内容:
withopen('data.csv', 'r') as f: header = f.readline() # 读取表头 data = f.read() # 读取剩余所有数据 process(header, data)
七、常见错误及解决方法
| | |
|---|
UnicodeDecodeError | | |
MemoryError | | |
ValueError: I/O operation on closed file | | |
TypeError: can't concat str to bytes | | |
八、总结
| |
|---|
| 小文件 | |
| 大文件 | |
| 文本模式 | 务必指定 encoding='utf-8',避免平台差异 |
| 二进制模式 | |
| 文件结束 | |
| 结合 with | |
read() 是文件操作中最基础也是最灵活的方法之一。掌握它的参数和行为,能够让你高效、安全地处理各种文件读取任务。