【发布时间】:2015-01-12 04:00:39
【问题描述】:
打开文件并读取其内容的简单方法是使用with:
with open ('file.txt', "r") as filehandle:
contents = filehandle.read()
但这不包括以 try/except 的方式排除文件打开错误:
try:
filehandle = open('file.txt', 'r')
contents = filehandle.read()
except IOError:
print('There was an error opening the file!')
sys.exit()
有没有办法将失败消息集成到 with 语句中,以便在打开失败时优雅退出,这将在比第二个示例更少的代码行中完成,但提供相同的功能?如果不是这样,还有什么比第二种形式更优雅(或极简)的吗?
【问题讨论】: