在Python中集成异常处理';与';
打开文件并读取其内容的一种简单方法是使用: 但这并不包括以在Python中集成异常处理';与';,python,exception-handling,Python,Exception Handling,打开文件并读取其内容的一种简单方法是使用: 但这并不包括以try/except会: try: filehandle = open('file.txt', 'r') contents = filehandle.read() except IOError: print('There was an error opening the file!') sys.exit() 有没有一种方法可以将失败消息集成到with语句中,以便在打开失败时它能够正常退出,而这样做的代码行
try/except
会:
try:
filehandle = open('file.txt', 'r')
contents = filehandle.read()
except IOError:
print('There was an error opening the file!')
sys.exit()
有没有一种方法可以将失败消息集成到with语句中,以便在打开失败时它能够正常退出,而这样做的代码行数比第二个示例少,但提供了相同的功能?如果不是这样,还有什么比第二种形式更优雅(或更简约)的吗
from contextlib import contextmanager
@contextmanager
def safe_open(fname,mode):
try:
fh = open(fname,mode)
except IOError:
print "ERROR OPENING FILE :",fname
sys.exit()
else:
yield fh
try:
fh.close()
except:
pass
with safe_open("nofile","rb") as f:
f.write("blah")
我不确定它是否更优雅,但我…这看起来不是很优雅,这只是因为您看到了实现。。。如果您只是从util import safe\u open执行
。。。然后使用它。那么它很优雅。。。(
from contextlib import contextmanager
@contextmanager
def safe_open(fname,mode):
try:
fh = open(fname,mode)
except IOError:
print "ERROR OPENING FILE :",fname
sys.exit()
else:
yield fh
try:
fh.close()
except:
pass
with safe_open("nofile","rb") as f:
f.write("blah")