Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unzip file in Python on all OSes?

Tags:

python

zip

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?

like image 472
tkbx Avatar asked Oct 14 '12 21:10

tkbx


People also ask

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.

How do you unzip all the contents in a zipped folder?

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.


1 Answers

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.

like image 92
phihag Avatar answered Oct 02 '22 04:10

phihag