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

原创 快来打我* 2025-01-17 00:12 123阅读 0赞

在 Python 中,可以使用 try/except 语句来优雅地处理文件 I/O 错误。

以下是一个基本的例子:

  1. def safe_open_file(file_path):
  2. try:
  3. # 打开文件
  4. file = open(file_path, 'r')
  5. content = file.read()
  6. file.close() # 关闭文件以释放资源
  7. return content
  8. except Exception as e:
  9. print(f"Error occurred while reading file: {e}")
  10. return None
  11. # 使用示例
  12. file_path = "example_file.txt"
  13. content = safe_open_file(file_path)
  14. if content is not None:
  15. print(content)

这个例子中,safe_open_file 函数尝试打开并读取指定的文件。如果在执行过程中发生异常(例如 I/O 错误),它会捕获这个异常,并打印出错误信息。最后返回 None 代表没有获取到有效内容。

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

发表评论

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

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

相关阅读