# Extract all contents from zip file
import zipfile
with zipfile.ZipFile('filename', 'r') as myzip: #'r' reads file, 'w' writes file
myzip.extractall()
# The zipfile will be extracted and content will be available in your working
# directory.
from zipfile import ZipFile
import zipfile
with ZipFile('test.zip') as myzip:
with myzip.open('Roughwork/textfile.text') as myfile:
print(myfile.readlines())Copy Code
import shutil
shutil.make_archive(output_filename, 'zip', dir_name)
import shutil
import zipfile
# base_name is the name of the zip file you want to create
# format is zip for zip file
# root_dir is the direct path of the folder or file you want to zip
shutil.make_archive(base_name='zip_file_name', format='zip', root_dir='data')
# read zip file from current path
with zipfile.ZipFile(file='zip_file_name.zip', mode='r') as zip_ref:
# create folder name extract_data in current directory with the extracted data
zip_ref.extractall(path='extract_data')
# Extract a single file from a zip file
with zipfile.ZipFile(file='zip_file_name.zip', mode='r') as zip_ref:
# Extract a file name called secrets.dat
zip_ref.extract(member='secrets.dat')
# extract a list of filename within a zip file
with zipfile.ZipFile(file='zip_file_name.zip', mode='r') as zip_obj:
# Get list of files names in zip
filenames = zip_obj.namelist()
# Iterate over the list of file names in given list & print them
for filename in filenames:
print(filename)
with ZipFile('spam.zip') as myzip:
with myzip.open('eggs.txt') as myfile:
print(myfile.read())