Python中文件操作通常使用`open()`函数,该函数接受两个参数:文件路径和打开模式。以下是Python文件操作的基本步骤和模式:
打开文件
file_obj = open('file_name.txt', 'mode')
其中`file_name.txt`是文件路径,`mode`是文件打开模式。
读取文件
读取整个文件内容:
with open('file_name.txt', 'r') as file_obj:
content = file_obj.read()
逐行读取文件内容:
with open('file_name.txt', 'r') as file_obj:
lines = file_obj.readlines()
for line in lines:
print(line)
写入文件
with open('file_name.txt', 'w') as file_obj:
file_obj.write('Hello, world!')
处理二进制文件
with open('image.jpg', 'rb') as file_obj:
处理二进制数据
文件模式
`r`:只读模式
`w`:只写模式,会覆盖原有内容
`a`:追加模式,在文件末尾添加内容
`r+`:读写模式
`w+`:读写模式,会覆盖原有内容
`a+`:追加和读取模式,在文件末尾添加内容
异常处理
try:
with open('file_name.txt', 'r') as file_obj:
content = file_obj.read()
except FileNotFoundError:
print("文件不存在")
finally:
file_obj.close()