尝试在Python中打开文件的行为可能会引发异常。如果我使用with
语句打开文件,是否可以捕获open
调用和相关__enter__
调用引发的异常而又不捕获with
块中代码引发的异常?
try:
with open("some_file.txt") as infile:
print("Pretend I have a bunch of lines here and don't want the `except` below to apply to them")
# ...a bunch more lines of code here...
except IOError as ioe:
print("Error opening the file:", ioe)
# ...do something smart here...
是否可以捕获open调用和相关
__enter__
调用引发的异常,而不能捕获with块中的代码引发的异常?
是的:
#!/usr/bin/env python3
import contextlib
stack = contextlib.ExitStack()
try:
file = stack.enter_context(open('filename'))
except OSError as e:
print('open() or file.__enter__() failed', e)
else:
with stack:
print('put your with-block here')
使用默认open()
功能时,__enter__()
不应引发任何有趣的异常,因此可以简化代码:
#!/usr/bin/env python
try:
file = open('filename')
except OSError as e:
print('open() failed', e)
else:
with file:
print('put your with-block here')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句