如何在 Python 中优雅地处理文件读写错误?

原创 阳光穿透心脏的1/2处 2025-03-08 13:33 116阅读 0赞

在Python中,可以使用try/except块来优雅地处理文件读写错误。下面是一个基本的例子:

  1. def safe_open(filename, mode):
  2. try:
  3. return open(filename, mode)
  4. except FileNotFoundError:
  5. print(f"{filename} not found. Can't proceed with the operation.")
  6. return None # Return None so that the calling function knows it failed
  7. except Exception as e:
  8. print(f"An error occurred while opening {filename}: {str(e)}}")
  9. return None # Return None so that the calling function knows it failed
  10. # 使用示例
  11. file = safe_open('non_existent_file.txt', 'r')
  12. if file is not None:
  13. content = file.read()
  14. if content:
  15. print(content)
  16. else:
  17. print("Failed to open file.")

这个函数会尝试打开文件,如果文件不存在或者在读操作中发生了其他错误,它会捕获这些异常,并打印出友好的错误消息。最后返回None,表示操作失败。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,116人围观)

还没有评论,来说两句吧...

相关阅读