Python通过 open() 函数读取文件,常用模式包括 'r'(文本只读)和 'rb'(二进制)。使用 with 语句可自动关闭文件,避免资源泄漏。还可以根据需求增加异常处理、编码指定等其他参数。大文件建议分块读取,或用 readlines() 获取行列表。二进制文件需用 'rb' 模式。
python读取文件的操作方法
在Python中,读取文件是常见的操作,主要通过内置的 open() 函数实现。以下是详细的操作方法和示例:
1. 基本读取方法
(1) 读取整个文件
python# 打开文件并读取全部内容(返回字符串)with open('example.txt', 'r', encoding='utf-8') as file:content = file.read()print(content)
参数说明:
'r':以只读模式打开。
encoding='utf-8':指定编码。
with 语句:自动关闭文件,避免资源泄漏。
(2) 逐行读取
python# 读取文件并逐行处理with open('example.txt', 'r', encoding='utf-8') as file:for line in file: # 文件对象是可迭代的print(line.strip()) # strip() 去除行尾换行符
(3) 读取所有行到列表
pythonwith open('example.txt', 'r', encoding='utf-8') as file:lines = file.readlines() # 返回列表,每行一个元素print(lines[0]) # 访问第一行
2. 高级读取方法
(1) 读取大文件
python# 避免内存不足,分块读取(如每次读取1024字节)with open('large_file.txt', 'r', encoding='utf-8') as file:while True:chunk = file.read(1024) # 每次读取1024字节if not chunk:breakprint(chunk)
(2) 使用 pathlib
pythonfrom pathlib import Pathcontent = Path('example.txt').read_text(encoding='utf-8')print(content)
3. 二进制文件读取
python# 读取图片、PDF等二进制文件with open('image.jpg', 'rb') as file: # 'rb' 表示二进制模式data = file.read()print(f"读取了 {len(data)} 字节")
4. 注意事项
文件路径:
相对路径(如 'data/example.txt')基于当前脚本目录。
绝对路径(如 '/home/user/data.txt')需确保权限正确。
异常处理:
pythontry:with open('nonexistent.txt', 'r') as file:print(file.read())except FileNotFoundError:print("文件不存在!")except IOError:print("读取文件时出错!")
文件关闭:
使用 with 语句会自动关闭文件,手动打开时需调用 file.close()。
5. 完整示例
python# 综合示例:统计文件行数和词数file_path = 'example.txt'try:with open(file_path, 'r', encoding='utf-8') as file:lines = file.readlines()word_count = sum(len(line.split()) for line in lines)print(f"行数: {len(lines)}, 词数: {word_count}")except FileNotFoundError:print(f"错误:文件 {file_path} 不存在!")
总结
文本文件:用 read()、readlines() 或遍历文件对象。
大文件:分块读取(read(size))。
二进制文件:用 'rb' 模式。
推荐:始终使用 with 和异常处理确保安全。
在Python中,读取文件是一个常见的操作,在数据处理工作中文件读取是基础操作但细节决定成败,以上就是python读取文件的操作方法介绍。