gpt4 book ai didi

python - 我应该如何在 Python 中捕获 `with open(filename)` 引发的异常?

转载 作者:太空宇宙 更新时间:2023-11-03 12:58:11 27 4
gpt4 key购买 nike

尝试在 Python 中打开文件的行为可能会引发异常。如果我使用 with 语句打开文件,是否可以捕获 open 调用和相关的 __enter__ 调用抛出的异常而不捕获异常由 with block 中的代码引发?

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...

这个问题不同于this older one因为旧的是关于编写上下文管理器,而不是使用熟悉的 with open

最佳答案

can I catch exceptions thrown by the open call and the related __enter__ call without catching exceptions raised by the code within the with block?

是的:

#!/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')

关于python - 我应该如何在 Python 中捕获 `with open(filename)` 引发的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32685951/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com