Python 文件操作指南
***文本由AI辅助生成***
Python 文件操作指南
Python 提供了丰富的内置函数来处理文件读写,让你可以方便地进行文件操作。下面是几种常见的文件操作方式:
1. 打开和关闭文件
使用 open() 函数打开文件,并使用 close() 方法关闭它。推荐使用上下文管理器(with)确保文件正确关闭。
# 打开文件,如果不存在则创建
f = open('test.txt', 'w')
# 使用with语句自动管理资源,无需显式调用close()
with open('test.txt', 'r') as f:
content = f.read()
print(content)
2. 读取文件
从文件中读取数据:
# 读取整份文件
with open('test.txt', 'r') as f:
data = f.read()
print(data)
# 行读取
with open('test.txt', 'r') as f:
for line in f:
print(line.strip())
# 读取特定数量的字符
with open('test.txt', 'r') as f:
chunk = 100
while True:
piece = f.read(chunk)
if not piece:
break
print(piece)
3. 写入文件
向文件写入数据:
# 写入模式覆盖文件
with open('test.txt', 'w') as f:
f.write('Hello, world!\n')
# 追加模式写入
with open('test.txt', 'a') as f:
f.write('Appending some more text.\n')
4. 二进制模式
读写二进制文件,如图片或音频文件:
# 读取二进制文件
with open('image.jpg', 'rb') as img_file:
image = img_file.read()
# 写入二进制文件
with open('copy.jpg', 'wb') as copy_file:
copy_file.write(image)
5. 修改文件位置
移动文件指针的位置:
with open('test.txt', 'r') as f:
f.seek(10) # 移动到第10个字节
print(f.read())
6. 删除文件
使用 os 模块删除文件:
import os
if os.path.exists('test.txt'):
os.remove('test.txt')
else:
print("File does not exist.")
7. 获取文件属性
利用 os 和 os.path 获取文件信息:
import os
print(os.path.isfile('test.txt')) # 判断是否存在
print(os.stat('test.txt').st_size) # 获取文件大小
8. 文件和目录遍历
使用 os 和 os.walk 遍历目录结构:
import os
for root, dirs, files in os.walk('.'):
for name in files:
print(os.path.join(root, name))
9. 复制文件
利用 shutil 模块复制文件:
import shutil
shutil.copy('test.txt', 'backup.txt')
10. 异常处理
处理可能发生的文件相关异常:
try:
with open('nonexistent.txt', 'r') as f:
f.read()
except FileNotFoundError:
print("File doesn't exist.")
Python 的文件操作功能强大而灵活,适合处理从简单的文本文件到复杂的二进制文件的各种需求。正确的使用文件处理不仅可以提高代码效率,还能保证数据安全性和完整性。
119

被折叠的 条评论
为什么被折叠?



