Unzipping files in Python
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!
Unzip all zipped files in a folder to that same folder using Python 2.7.5
Below is the code that worked for me:
import os, zipfile
dir_name = 'C:\\SomeDirectory'
extension = ".zip"
os.chdir(dir_name) # change directory from working dir to dir with files
for item in os.listdir(dir_name): # loop through items in dir
if item.endswith(extension): # check for ".zip" extension
file_name = os.path.abspath(item) # get full path of files
zip_ref = zipfile.ZipFile(file_name) # create zipfile object
zip_ref.extractall(dir_name) # extract file to dir
zip_ref.close() # close file
os.remove(file_name) # delete zipped file
Looking back at the code I had amended, the directory was getting confused with the directory of the script.
The following also works while not ruining the working directory. First remove the line
os.chdir(dir_name) # change directory from working dir to dir with files
Then assign file_name as
file_name = dir_name + "/" + item
Unzipping multiple file without loosing the original creation date
Actually opening multiple zip files manually keeps the dates, at least on macOS.
Search for the files you need to unzip, select -> open.
Downloading and unzipping a .zip file without writing to disk
My suggestion would be to use a StringIO
object. They emulate files, but reside in memory. So you could do something like this:
# get_zip_data() gets a zip archive containing 'foo.txt', reading 'hey, foo'
import zipfile
from StringIO import StringIO
zipdata = StringIO()
zipdata.write(get_zip_data())
myzipfile = zipfile.ZipFile(zipdata)
foofile = myzipfile.open('foo.txt')
print foofile.read()
# output: "hey, foo"
Or more simply (apologies to Vishal):
myzipfile = zipfile.ZipFile(StringIO(get_zip_data()))
for name in myzipfile.namelist():
[ ... ]
In Python 3 use BytesIO instead of StringIO:
import zipfile
from io import BytesIO
filebytes = BytesIO(get_zip_data())
myzipfile = zipfile.ZipFile(filebytes)
for name in myzipfile.namelist():
[ ... ]
Related Topics
Way to Change Google Chrome User Agent in Selenium
Googletrans Stopped Working with Error 'Nonetype' Object Has No Attribute 'Group'
How to Get the Input from the Tkinter Text Widget
Add Leading Zeros to Strings in Pandas Dataframe
How to Install Python Modules Without Root Access
Converting from a String to Boolean in Python
What Is the Use of Join() in Python Threading
Are Tuples More Efficient Than Lists in Python
How to Find Script's Directory
Find the Max of Two or More Columns with Pandas
Pandas: Convert Categories to Numbers
Merge Lists That Share Common Elements
How to Include Third Party Python Libraries in Google App Engine
Explaining the 'Self' Variable to a Beginner
How to Zip Two Differently Sized Lists, Repeating the Shorter List
What Is the Fastest Way to Flatten Arbitrarily Nested Lists in Python