Is there a simple Python function that would allow unzipping a .zip file like so?:
unzip(ZipSource, DestinationDirectory)
I need the solution to act the same on Windows, Mac and Linux: always produce a file if the zip is a file, directory if the zip is a directory, and directory if the zip is multiple files; always inside, not at, the given destination directory
How do I unzip a file in Python?
Python Zipfile Module Its extractall() function is used to extract all the files and folders present in the zip file. We can use zipfile. extractall() function to unzip the file contents in the same directory as well as in a different directory.
To unzip (extract) files or folders from a zipped folder To unzip all the contents of the zipped folder, press and hold (or right-click) the folder, select Extract All, and then follow the instructions.
Use the zipfile
module in the standard library:
import zipfile,os.path def unzip(source_filename, dest_dir): with zipfile.ZipFile(source_filename) as zf: for member in zf.infolist(): # Path traversal defense copied from # http://hg.python.org/cpython/file/tip/Lib/http/server.py#l789 words = member.filename.split('/') path = dest_dir for word in words[:-1]: while True: drive, word = os.path.splitdrive(word) head, word = os.path.split(word) if not drive: break if word in (os.curdir, os.pardir, ''): continue path = os.path.join(path, word) zf.extract(member, path)
Note that using extractall
would be a lot shorter, but that method does not protect against path traversal vulnerabilities before Python 2.7.4. If you can guarantee that your code runs on recent versions of Python.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With