Python中文件操作:读写错误示例
在Python中,文件操作可能会出现各种错误。以下是一些常见的读写错误示例:
文件不存在:
try:
with open('non_existent_file.txt', 'r') as f:
print(f.read())
except FileNotFoundError:
print("File not found.")
文件模式不正确:
try:
with open('test.txt', 'w') as f: # 应为'x',创建文件不存在时会自动创建
f.write("Hello, World!")
with open('test.txt', 'r') as f:
print(f.read())
except FileNotFoundError:
print("File not found.")
写入权限不足:
try:
with open('/private/etc/config.txt', 'w') as f: # 如果目标文件在私有目录,需要以root权限运行
f.write("This is a私有 file.")
with open('/private/etc/config.txt', 'r') as f:
print(f.read())
except PermissionError:
print("Permission denied for the private file.")
以上就是Python中文件操作可能出现的一些读写错误示例。
还没有评论,来说两句吧...