I read through the zipfile modules docs, but couldn't understand how to unzip a file, only how to zip a file. How do I unzip all the contents of a zip file into the same directory?pythonzipunzipzipfile
import zipfile zip_ref = zipfile.ZipFile(path_to_zip_file, 'r') zip_ref.extractall(directory_to_extract_to) zip_ref.close()
That's pretty much it!
extractall method, if you're using Python 2.6+
zip = ZipFile('file.zip') zip.extractall()
If you are using Python 3.2 or later:
import zipfile with zipfile.ZipFile("file.zip","r") as zip_ref: zip_ref.extractall("targetdir")
You dont need to use the close or try/catch with this as it uses the context manager construction
import os zip_file_path = "C:\AA\BB" file_list = os.listdir(path) abs_path =  for a in file_list: x = zip_file_path+'\\'+a print x abs_path.append(x) for f in abs_path: zip=zipfile.ZipFile(f) zip.extractall(zip_file_path)
This does not contain validation for the file if its not zip. If the folder contains non .zip file it will fail.