If you try to extract a compressed file from the address stored in the variable local with the following code, and if there is no compressed file called local and a FileNotFoundError occurs, I would like to skip the processing for local.
How can I change the code below to solve the problem above...?
Codepython python3 exception
You can use
These nested with statements can be combined to reduce indentation.
On the , we have captured all exceptions (
FileNotFoundError) that occurred within the with block.Instead, you can use
contextlib.ExitStack to handle only exceptions in the context expression (where you open the file with
zipfile.ZipFile in this example).
Above, the with statement should be at the end of the for statement, and
continue omits the with statement.For example, you can use
return at the end of a function.However, in some cases, the with sentence is not placed in such a place.In that case, I think it would be good to combine the
contextlib.suppress introduced above.
Other references include "Catch exceptions from the
__enter__ method" in the official documentation.
© 2022 OneMinuteCode. All rights reserved.