文件操作
文件操作基础
文件操作是编程中最常见的任务之一。Python提供了简洁而强大的文件操作接口,让你可以轻松地读写各种类型的文件。
# 打开文件的最基本方式
file = open('example.txt', 'r')
content = file.read()
file.close()
使用with语句
with语句是Python中管理资源的最佳方式,它能确保文件在使用后自动关闭,即使发生异常也不会导致资源泄露。
# 使用with语句读取文件
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# 文件会自动关闭,无需手动调用close()
文件打开模式
Python支持多种文件打开模式,根据需求选择合适的模式非常重要。
# 只读模式(默认)
with open('example.txt', 'r') as f:
content = f.read()
# 写入模式(覆盖)
with open('output.txt', 'w') as f:
f.write('Hello, World!')
# 追加模式
with open('log.txt', 'a') as f:
f.write('New log entry\n')
# 二进制读取
with open('image.jpg', 'rb') as f:
data = f.read()
# 二进制写入
with open('copy.jpg', 'wb') as f:
f.write(data)
读取文件的多种方式
Python提供了多种读取文件内容的方法,适用于不同的场景。
# 读取整个文件
with open('data.txt', 'r') as f:
all_content = f.read()
# 逐行读取(内存友好)
with open('large_file.txt', 'r') as f:
for line in f:
print(line.strip())
# 读取所有行到列表
with open('data.txt', 'r') as f:
lines = f.readlines()
# 读取一行
with open('data.txt', 'r') as f:
first_line = f.readline()
second_line = f.readline()
写入文件
写入文件时,可以选择覆盖写入或追加内容。
# 覆盖写入
with open('output.txt', 'w') as f:
f.write('第一行\n')
f.write('第二行\n')
f.write('第三行\n')
# 追加内容
with open('output.txt', 'a') as f:
f.write('新添加的一行\n')
# 写入多行
lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
with open('output.txt', 'w') as f:
f.writelines(lines)
CSV文件处理
CSV(逗号分隔值)是最常见的数据交换格式之一。Python的csv模块提供了便捷的处理方式。
import csv
# 写入CSV文件
data = [
['姓名', '年龄', '城市'],
['张三', 25, '北京'],
['李四', 30, '上海'],
['王五', 28, '广州']
]
with open('people.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(data)
# 读取CSV文件
with open('people.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(row)
# 使用字典方式读写CSV
with open('people.csv', 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
print(f"{row['姓名']}来自{row['城市']}")
文件和目录操作
除了读写文件内容,Python还可以进行文件系统层面的操作。
import os
import shutil
# 检查文件是否存在
if os.path.exists('example.txt'):
print('文件存在')
# 获取文件信息
size = os.path.getsize('example.txt')
print(f'文件大小: {size} 字节')
# 列出目录内容
files = os.listdir('.')
print(files)
# 创建目录
os.makedirs('new_folder/subfolder', exist_ok=True)
# 重命名文件
os.rename('old_name.txt', 'new_name.txt')
# 删除文件
os.remove('unwanted.txt')
# 复制文件
shutil.copy('source.txt', 'destination.txt')
# 删除空目录
os.rmdir('empty_folder')
最佳实践
- 始终使用
with语句管理文件,确保资源正确释放 - 处理文本文件时指定编码(如
encoding='utf-8') - 大文件读取时使用逐行读取,避免内存溢出
- 写入CSV时设置
newline=''避免多余空行 - 在进行文件操作前检查文件是否存在,避免运行时错误
掌握文件操作是Python编程的基本功,无论是数据处理、日志记录还是配置管理,都离不开文件操作。