Python文件处理的核心方法包括文件打开、读取、写入及资源管理,结合权威信息源整理如下:
一、文件打开与关闭
-
推荐使用
with
语句 :自动管理文件上下文,确保文件在操作完成后正确关闭,避免资源泄露。 -
基本语法 :
with open('filename', 'mode') as file:
,模式如'r'
(读取)、'w'
(写入)、'a'
(追加)等。
二、文件读取方式
-
一次性读取
适用于小文件,直接使用
read()
方法获取全部内容。 -
逐行读取
通过
for line in file
迭代,内存占用低,适合大文件处理。 -
按块读取
分块处理(如
chunk_size=8192
),适用于超大文件,避免内存溢出。
三、文件写入操作
-
覆盖写入 :使用
'w'
模式创建新文件或覆盖原有内容。 -
追加写入 :使用
'a'
模式在文件末尾追加内容。 -
批量写入 :通过循环或列表一次性写入多行数据。
四、编码与异常处理
-
指定编码 :始终使用
encoding='utf-8'
避免跨平台字符问题。 -
异常处理 :在
with
语句中嵌套try-except
块,确保操作安全。
五、进阶技巧
-
文件复制与移动 :使用
shutil.copy()
、shutil.move()
等函数。 -
结构化数据处理 :结合
pandas
处理CSV文件,或使用json
模块操作JSON数据。
示例代码
# 读取文件
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
# 逐行读取
with open('large_file.txt', 'r', encoding='utf-8') as file:
for line in file:
if 'ERROR' in line:
print(line.strip())
# 写入文件
with open('output.txt', 'w', encoding='utf-8') as file:
file.write('Hello, World!\n')
# 大文件分块处理
def process_large_file(filename, chunk_size=8192):
with open(filename, 'r', encoding='utf-8') as file:
while True:
chunk = file.read(chunk_size)
if not chunk:
break
process_chunk(chunk)
通过以上方法,可高效、安全地完成文件读写任务,满足不同场景需求。