The example code opens the specified ZIP file, prints the list of file names in the archive, extracts all files to the current working directory, and extracts specific files to a specified directory. Additionally, it handles the KeyError and BadZipfile exceptions when a requested file cannot be found in the archive or when the archive is invalid or corrupted:
import zipfile
# define the filename of the ZIP file to extract
filename: str = 'file.zip'
if __name__ == '__main__':
try:
# open the ZIP file for reading
with zipfile.ZipFile(filename) as file:
# print the list of file names in the archive
print(file.namelist())
# extract all files from the archive to the current working directory
file.extractall()
# extract specific files from the archive to a specified directory
# by passing in a list of file names and a target directory path
file.extractall("directory", ['main.py', 'helpers.py', 'math.py'])
# handle the KeyError exception when a requested file is not found in the archive
except KeyError as e:
print('{}.'.format(f'{e}'.strip('"')))
# handle the BadZipfile exception when the archive is invalid or corrupted
except zipfile.BadZipfile as e:
print(f'{filename} is not a valid ZIP archive.')
I sincerely hope that you find this code helpful. If you wish to learn more about Python, please subscribe to our newsletter today and continue your Python learning journey with us!