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...?
Code
#coding:utf-8
import zipfile
local = 'local.zip'
with zipfile.ZipFile(local, 'r') as zf: Read the #zip file.How do I handle exceptions when I can't find a file...
files=[ info.filename for info in zf.infolist() if info.filename.endswith('.txt') ]
You can use contextlib.suppress.
#!/usr/bin/python3
import zipfile
from contextlib import suppress
with suppress (FileNotFoundError):
with zipfile.ZipFile("file.zip", 'r') as zf:
print("success:",zf)#some action
These nested with statements can be combined to reduce indentation.
with suppress (FileNotFoundError), zipfile.ZipFile("file.zip", 'r') as zf:
print("success:",zf)#some action
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).
from contextlib import ExitStack
# approximately
# Escape with continue from block as end of for statement
with ExitStack() as stack:
try:
zf = stack.enter_context(zipfile.ZipFile("file.zip", 'r')
except FileNotFoundError:
continue
print("success:",zf)#some action
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.
#!/usr/bin/python3
import zipfile
from contextlib import suppress, ExitStack
class SkipError (Exception):
pass
with suppress(SkipError), ExitStack() as stack:
try:
zf = stack.enter_context(zipfile.ZipFile("file.zip", 'r')
except FileNotFoundError:
raise SkipError ("zip file not found")
print("success:",zf)#some action
Other references include "Catch exceptions from the __enter__ method" in the official documentation.
3079 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
2564 I want to display multiple lines with FFmpeg subtitles.
1950 I want to connect to the webcam from WSL(ubuntu)
1921 M2 Mac fails to install rbenv install 3.1.3 due to errors
1788 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2026 OneMinuteCode. All rights reserved.