Python文件操作:读写和错误处理
在Python中,进行文件操作主要是通过内置的open()
函数。这里我们将主要介绍如何读写文件以及错误处理。
打开文件:
# 打开文件并以文本模式读取
file = open('example.txt', 'r')
# 打开文件并以二进制模式写入
file = open('image.jpg', 'wb')
读取文件内容:
content = file.read() # 读取全部内容
print(content) # 输出文件内容
lines = file.readlines() # 按行读取
for line in lines:
print(line.strip()) # 打印每行,去尾空白
写入文件:
file.write('Hello, World!') # 写入一行文本
data = b'binary data' # 转换为二进制数据
file.write(data) # 写入二进制数据
lines = ['line1', 'line2', 'line3']]
file.writelines(lines) # 写入多行文本
错误处理:
try:
# 文件操作代码
except FileNotFoundError:
print("File not found! Please check the file path.")
except PermissionError:
print("Permission denied! Please make sure you have the right permissions.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
# 关闭文件
if 'file' in locals():
file.close()
以上就是Python中进行文件读写以及错误处理的基本操作。
还没有评论,来说两句吧...