如何在Python中优雅地处理文件IO错误?
在 Python 中,可以使用 try/except
语句来优雅地处理文件 I/O 错误。
以下是一个基本的例子:
def safe_open_file(file_path):
try:
# 打开文件
file = open(file_path, 'r')
content = file.read()
file.close() # 关闭文件以释放资源
return content
except Exception as e:
print(f"Error occurred while reading file: {e}")
return None
# 使用示例
file_path = "example_file.txt"
content = safe_open_file(file_path)
if content is not None:
print(content)
这个例子中,safe_open_file
函数尝试打开并读取指定的文件。如果在执行过程中发生异常(例如 I/O 错误),它会捕获这个异常,并打印出错误信息。最后返回 None
代表没有获取到有效内容。
还没有评论,来说两句吧...