Unzipping files in Python
Solution 1
import zipfile
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
zip_ref.extractall(directory_to_extract_to)
That's pretty much it!
Solution 2
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.
Solution 3
zipfile
is a somewhat low-level library. Unless you need the specifics that it provides, you can get away with shutil
's higher-level functions make_archive
and unpack_archive
.
make_archive
is already described in this answer. As for unpack_archive
:
import shutil
shutil.unpack_archive(filename, extract_dir)
unpack_archive
detects the compression format automatically from the "extension" of filename
(.zip
, .tar.gz
, etc), and so does make_archive
. Also, filename
and extract_dir
can be any path-like objects (e.g. pathlib.Path instances) since Python 3.7.
Solution 4
Use the extractall
method, if you're using Python 2.6+
zip = ZipFile('file.zip')
zip.extractall()
Solution 5
You can also import only ZipFile
:
from zipfile import ZipFile
zf = ZipFile('path_to_file/file.zip', 'r')
zf.extractall('path_to_extract_folder')
zf.close()
Works in Python 2 and Python 3.
John Howard
Updated on July 10, 2022Comments
-
John Howard almost 2 years
I read through the
zipfile
documentation, 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? -
asonnenschein over 10 yearsDon't you have to specify a destination (zip.extractall(destination))?
-
Dan Gayle over 10 yearsNot if you're just extracting into the same directory as the zipfile
-
iratzhash about 8 yearswhat if the contents of the .zip archive are same, in all .zip archives? how to rename the content before extracting? example: 1.zip 2.zip.. all contain content.txt : extract all like 1content.txt 2content.txt?
-
FelixEnescu over 7 yearsZipFile also works as a context manager in 2.7 or later: docs.python.org/2/library/zipfile.html#zipfile.ZipFile
-
Brian Leishman almost 7 years@DanGayle this appears to be extracting the zip file into the current working directory, NOT the location of the zip file
-
Dave Forgac almost 7 years@iratzhash I typically create a new temporary directory for the contents using tempfile: docs.python.org/3/library/tempfile.html I unzip to the temporary directory and the move / organize the files from there.
-
Debug255 over 6 years@3kstc I would
from zipfile import ZipFile
. When using it, you no longer need to usezipfile.ZipFile
, and can useZipFile(zip_file_name)
. -
Debug255 over 6 years@iratzhash I realize you commented 1.5 years ago. But just so others know, usually contents within a zip file are read-only. A good answer is here by "bouke"
-
Agile Bean over 5 yearsfor me, ZipFile() didn't work but zipfile.ZipFile() did - after import zipfile
-
simhumileco over 5 yearsThank you for your attention @MylesHollowed However, this is not a copy from the accepted answer. I agree that they are similar to each other, but they are different. This is also indicated by your comment, because the accepted one is definitely better for you than mine. If it was a copy, it would be the same... For someone my answer may be valuable because it is perhaps more readable and as you noticed import less code... It is because of these differences that I decided to put my answer to give an alternative. Is not that why we can put other answers after accepting one? All the best
-
SnowOnion about 5 yearsHow to deal with docs.python.org/3.6/library/zipfile.html#zipfile.BadZipFile exception? Generally, what is the best practice to use try/except with context manager (with-statement)?
-
ntg about 5 yearsthnx, note: There is no zipfile library, no need to pip install, zipfile is already there...
-
Martin Thoma almost 5 yearsI'd add:
from tempfile import mkdtemp; directory_to_extract_to = mkdtemp()
-
Umar.H over 4 years
zipfile
+pathlib
= win. mind if i slightly update your answer? -
simhumileco over 4 yearsWhat's wrong with this answer? Why did someone give her a negative point? After all, it is the answer to the question and is distinguished by its simplicity compared to other answers, which may be important for some people who are looking for an answer. Isn't it?
-
MikeF about 4 years@MylesHollowed
import zipfile.ZipFile
generatesModuleNotFoundError: No module named 'zipfile.ZipFile'; 'zipfile' is not a package
in 3.6.5. I am open to it being operator error on my part, but I don't know what it is. -
Boris Verkhovskiy almost 4 yearsYou need to
zip.close()
at the end if you don't use awith
statement like the other answers suggest. -
Ben Dalling over 3 years@MikeF I had the same problem with Python 3.8.5 but the workaround was to use
from zipfile import ZipFile
. Hope this helps. -
Charlie Parker over 3 yearswhy not just do
tar -xvzf path_file
in your case? -
Charlie Parker over 3 yearsis there a reason to avoid
os.system(f'tar -xvzf {filename}')
and instead use zipfile (e.g.zip = ZipFile('file.zip'); zip.extractall() )
orshutil.unpack_archive(filename, extract_dir)
? -
Perry over 3 yearsZIP files are not tar files. Unless you have a special version of
tar
which handles ZIP archives, your command wont work at all.tar
with the-z
option processes gzipped tar archives (generally files with extensions.tgz
or.tar.gz
) -
Nicoolasens over 3 yearsto me it's strictly similar
-
msoutopico about 3 yearsThis method doesn't work when the zip file has a custom extension, e.g. (
.omt
for OmegaT project packages). It givesraise ReadError("Unknown archive format '{0}'".format(filename))
. -
fonini about 3 years@msoutopico you can specify thje format explicitly:
shutil.unpack_archive(filename, extract_dir, format)
-
Fareanor about 3 years@CharlieParker The main reason is portability.
system
calls are OS dependent. For example,tar
would not be available on Windows. -
Charlie Parker almost 3 yearswhat is wrong with
os.system(f'tar -xvzf {path2zip} -C {path2unzip}/')
? -
Charlie Parker almost 3 yearswhat is wrong with
os.system(f'tar -xvzf {path2zip} -C {path2unzip}/')
? -
fonini almost 3 years@CharlieParker you have already asked the same thing in a comment to another answer, and that comment was answered: stackoverflow.com/questions/3451111/unzipping-files-in-python/…
os.system
is not portable, opens up security issues, is harder to use correctly (e.g. your proposal fails when the paths have special characters), and is less readable. -
Ryan Loggerythm over 2 yearsfor passwords use: with ZipFile(zip_file_path, 'r') as zipObj: zipObj.extractall(output_folder, pwd=b'myPassword')
-
tista3 over 2 yearsI do not recommend zipfile. I had problems to extract files added in existing zip file. This can be done with total commander, which addz new file entry and file database at the end of the file.
zipfile
extracted only the old files.shutil.unpack_archive
does not have this problem. -
Selfcontrol7 over 2 yearsThis minimal code will still do the job without problem:
z = ZipFile(path_to_zip_file)
z.extractall(directory_to_extract_to)