The act of attempting to open a file in Python can throw an exception. If I'm opening the file using the with
statement, 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?
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 question is different from this older one in that the older one is about writing a context manager, rather than using the familiar with open
.