Skip to content

Instantly share code, notes, and snippets.

@cesandoval
Created July 24, 2012 20:13
Show Gist options
  • Save cesandoval/3172360 to your computer and use it in GitHub Desktop.
Save cesandoval/3172360 to your computer and use it in GitHub Desktop.
Extracts files on a zip file into a given directory, if no directory is given, it extracts the files into the zip file directory.
import zipfile
import os
#Extracts files on a zip file into a given directory, if no directory is given,
#it extracts the files into the zip file directory.
def unzip_file(zip_file, my_path=None):
zip_file = zipfile.ZipFile(zip_file) #open the zip file
if my_path != None: #if directory is given, and doesn't exist, create directory.
if not os.path.isdir(my_path):
os.makedirs(my_path)
for f in zip_file.namelist(): #extract all the files into the given directory
zip_file.extract(f, my_path=None)
else: #if no directory is given, extract the files into the zipfiles's directory.
for f in zip_file.namelist():
zip_file.extract(f)
zip_file = 'C:\Users\carlos\Desktop\python\Json_File.zip' #set the zipfile's directory.
#my_path = 'C:\Users\carlos\Desktop\python\Json_File' #set the directory to extract files.
unzip_file(zip_file)
@bengolder
Copy link

I'd recommend not making the OSError silent. Let it happen if there's an error. Otherwise you won't know that something went wrong.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment