I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder.
So I want to end up with a zip file with a single folder with files in.
I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject.
I started out with this:
def addFolderToZip(myZipFile,folder): folder = folder.encode('ascii') #convert path to ascii for ZipFile Method for file in glob.glob(folder+"/*"): if os.path.isfile(file): print file myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) elif os.path.isdir(file): addFolderToZip(myZipFile,file) def createZipFile(filename,files,folders): curTime=strftime("__%Y_%m_%d", time.localtime()) filename=filename+curTime; print filename zipFilename=utils.getFileName("files", filename+".zip") myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing for file in files: file = file.encode('ascii') #convert path to ascii for ZipFile Method if os.path.isfile(file): (filepath, filename) = os.path.split(file) myZipFile.write( file, filename, zipfile.ZIP_DEFLATED ) for folder in folders: addFolderToZip(myZipFile,folder) myZipFile.close() return (1,zipFilename) (success,filename)=createZipFile(planName,files,folders);
Taken from: http://mail.python.org/pipermail/python-list/2006-August/396166.html
Which gets rid of all folders and puts all files in the target folder (and its subfolders) into a single zip file. I couldnt get it to add an entire folder.
If I feed the path to a folder in myZipFile.write, I get
IOError: [Errno 13] Permission denied: '..\packed\bin'
Any help is much welcome.
Related question: How do I zip the contents of a folder using python (version 2.5)?
But what if we want to add files to an existing zip? It's simple enough, we just need to open the file in append mode. Opening an existing zip file in write mode will erase the zip, so be careful when you're using that mode. Finally, you can write a program to extract zip files to disk in just a few lines.
Locate the file or folder that you want to zip. Press and hold (or right-click) the file or folder, select (or point to) Send to, and then select Compressed (zipped) folder. A new zipped folder with the same name is created in the same location.
With python 3.9, pathlib & zipfile module you can create a zip files from anywhere in the system. It is neat, typed, and has less code.
You can also use shutil
import shutil zip_name = 'path\to\zip_file' directory_name = 'path\to\directory' # Create 'path\to\zip_file.zip' shutil.make_archive(zip_name, 'zip', directory_name)
This will put the whole folder in the zip.
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