如何在 Python 中优雅地处理文件读写错误?
在Python中,可以使用try/except块来优雅地处理文件读写错误。下面是一个基本的例子:
def safe_open(filename, mode):
try:
return open(filename, mode)
except FileNotFoundError:
print(f"{filename} not found. Can't proceed with the operation.")
return None # Return None so that the calling function knows it failed
except Exception as e:
print(f"An error occurred while opening {filename}: {str(e)}}")
return None # Return None so that the calling function knows it failed
# 使用示例
file = safe_open('non_existent_file.txt', 'r')
if file is not None:
content = file.read()
if content:
print(content)
else:
print("Failed to open file.")
这个函数会尝试打开文件,如果文件不存在或者在读操作中发生了其他错误,它会捕获这些异常,并打印出友好的错误消息。最后返回None,表示操作失败。
还没有评论,来说两句吧...