473,320 Members | 1,957 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

How to Zip a Directory with Python (using zipfile)

I'm relatively new to python, and am trying to zip a directory containing several levels of files and folders. I can use the walk function to name each file in my directory, and I can use zipfile to zip a flat number of files in one folder, but I am having heck of a time trying to zip the whole directory. I want to zip it all to a file called "help.zip", and I want it to retain the original file structure.

Of my several tries, here is the latest:
Expand|Select|Wrap|Line Numbers
  1. import zipfile, os
  2.  
  3. def main():
  4.     zip = "help3.zip"
  5.     directory = "//groupstore/workgroups/documentation/test"
  6.     toZip(directory)
  7.  
  8.  
  9. def toZip(directory):
  10.     zippedHelp = zipfile.ZipFile(zip, "w", compression=zipfile.ZIP_DEFLATED )
  11.  
  12.     list = os.listdir(directory)
  13.  
  14.     for entity in list:
  15.         each = os.path.join(directory,entity)
  16.  
  17.         if os.path.isfile(each):
  18.             print each
  19.             zippedHelp.write(each,zipfile.ZIP_DEFLATED)
  20.         else:
  21.             addFolderToZip(zippedHelp,entity)
  22.  
  23.     zippedHelp.close()
  24.  
  25. #def addFolderToZip(zippedHelp,folder):
  26.  
  27.     for file in folder:
  28.             if os.path.isfile(file):
  29.                 zippedHelp.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED)
  30.             elif os.path.isdir(file):
  31.                 addFolderToZip(zippedHelp,file)
  32. main()
  33.  
Nov 3 '08 #1
10 38538
bvdet
2,851 Expert Mod 2GB
Here's another thread that may be relevant: http://bytes.com/forum/thread845051.html
Nov 4 '08 #2
bvdet
2,851 Expert Mod 2GB
Here's a script that I use to backup the contents of a directory and it's subdirectories. It can easily be adjusted to backup only the directory contents or files with specific extensions. The file path is saved in the archive.
Expand|Select|Wrap|Line Numbers
  1. import zipfile, os
  2.  
  3. def makeArchive(fileList, archive):
  4.     """
  5.     'fileList' is a list of file names - full path each name
  6.     'archive' is the file name for the archive with a full path
  7.     """
  8.     try:
  9.         a = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)
  10.         for f in fileList:
  11.             print "archiving file %s" % (f)
  12.             a.write(f)
  13.         a.close()
  14.         return True
  15.     except: return False
  16.  
  17. def dirEntries(dir_name, subdir, *args):
  18.     '''Return a list of file names found in directory 'dir_name'
  19.     If 'subdir' is True, recursively access subdirectories under 'dir_name'.
  20.     Additional arguments, if any, are file extensions to match filenames. Matched
  21.         file names are added to the list.
  22.     If there are no additional arguments, all files found in the directory are
  23.         added to the list.
  24.     Example usage: fileList = dirEntries(r'H:\TEMP', False, 'txt', 'py')
  25.         Only files with 'txt' and 'py' extensions will be added to the list.
  26.     Example usage: fileList = dirEntries(r'H:\TEMP', True)
  27.         All files and all the files in subdirectories under H:\TEMP will be added
  28.         to the list.
  29.     '''
  30.     fileList = []
  31.     for file in os.listdir(dir_name):
  32.         dirfile = os.path.join(dir_name, file)
  33.         if os.path.isfile(dirfile):
  34.             if not args:
  35.                 fileList.append(dirfile)
  36.             else:
  37.                 if os.path.splitext(dirfile)[1][1:] in args:
  38.                     fileList.append(dirfile)
  39.         # recursively access file names in subdirectories
  40.         elif os.path.isdir(dirfile) and subdir:
  41.             print "Accessing directory:", dirfile
  42.             fileList.extend(dirEntries(dirfile, subdir, *args))
  43.     return fileList
  44.  
  45. if __name__ == '__main__':
  46.     folder = r'D:\Zip_Files\611 Lenox'
  47.     zipname = r'D:\Zip_Files\611 Lenox\test.zip'
  48.     makeArchive(dirEntries(folder, True), zipname)
  49.  
HTH
Nov 4 '08 #3
Here's another thread that may be relevant: http://bytes.com/forum/thread845051.html

Thanks! I appreciate the help!
Nov 4 '08 #4
Here's a script that I use to backup the contents of a directory and it's subdirectories. It can easily be adjusted to backup only the directory contents or files with specific extensions. The file path is saved in the archive.

Thank you!! Yay. I used your script to make mine work and I'm getting a better understanding of recursive functions. That was definitely where my hangup had been. Thanks again!!
Nov 4 '08 #5
@bvdet
Thanks, this is just what i was looking for in my pys60 app :D. Thanks again for the help :)
Feb 27 '09 #6
Nakubu
2
you can also do this, which is MUCH more concise:

Expand|Select|Wrap|Line Numbers
  1. def recursive_zip(zipf, directory, folder=None):
  2.     list = os.listdir(directory)
  3.  
  4.     for file in list:
  5.         if os.path.isfile(file):
  6.             zipf.write(file, folder, zipfile.ZIP_DEFLATED)
  7.         elif os.path.isdir(file):
  8.             recursive_zip(zipf, os.path.join(directory, file), file)
Mar 31 '10 #7
bvdet
2,851 Expert Mod 2GB
Nakubu,

Thank you for your contribution. Please use code tags when posting code in the future.

It's not a good idea to use list and file as names of variables. The built-in functions list() and file() will be masked until the objects are deleted.

I have a question. Is zipf an open file object? It would be helpful to others reading this thread if you would post sample code that creates the file object, calls recursive_zip(), and closes the file object.

BV - Moderator
Mar 31 '10 #8
Nakubu
2
here's a revised version:

Expand|Select|Wrap|Line Numbers
  1. def recursive_zip(zipf, directory, folder=None):
  2.     nodes = os.listdir(directory)
  3.  
  4.     for item in nodes:
  5.         if os.path.isfile(item):
  6.             zipf.write(item, folder, zipfile.ZIP_DEFLATED)
  7.         elif os.path.isdir(item):
  8.             recursive_zip(zipf, os.path.join(directory, item), item)
  9.  
  10.  
zipf is an opened zipfile.ZipFile instance. For example:

Expand|Select|Wrap|Line Numbers
  1. zipf = zipfile.ZipFile(zip, "w", compression=zipfile.ZIP_DEFLATED )
  2. path = '/Users/nakubu/some_folder'
  3. recursive_zip(zipf, path) //leave the first folder as None, as path is root.
  4. zipf.close()
  5.  
Mar 31 '10 #9
I found Nakubu's function helpful, but needed to modify it in several ways. Hope this helps someone:
Expand|Select|Wrap|Line Numbers
  1. def recursive_zip(zipf, directory, folder = ""):
  2.    for item in os.listdir(directory):
  3.       if os.path.isfile(os.path.join(directory, item)):
  4.          zipf.write(os.path.join(directory, item), folder + os.sep + item)
  5.       elif os.path.isdir(os.path.join(directory, item)):
  6.          recursive_zip(zipf, os.path.join(directory, item), folder + os.sep + item)
  7.  
Oct 17 '10 #10
These are all good, but IMHO, os.walk rocks and does the hard stuff for you.
Jun 17 '11 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: Tung Wai Yip | last post by:
Can I add empty directory using zipfile? When I try to add a directory it complains that it is not a file. tung
0
by: Helmut Zeisel | last post by:
I want to build a static extension of Python using SWIG and VC++ 6.0 as described in http://www.swig.org/Doc1.3/Python.html#n8 for gcc. My file is testerl.i: ========================= %module...
1
by: ralobao | last post by:
I have this code: try: file = zipfile.ZipFile(nome_arquivo) Gauge.start() #inicia o Gauge for element in file.namelist(): try: newFile = open(diretorio + element,"wb") except: newFile =...
2
by: Phil Galey | last post by:
Using the following, you can determine the size of a file: Dim fi As New IO.FileInfo(<Path to file>) MsgBox(fi.Length) .... but what about the size of a directory? The IO.DirectoryInfo object...
1
by: WolfsonNYC | last post by:
Anyone know how to enable Directory Browsing using the Cassini web server on .Net 2.0 ? Right now it says HTTP Error 403 - Forbidden when I go to a folder on my web site. Thanks, JW
1
by: krithika.sridhar | last post by:
Hi, I'm using : python setup.py bdist_rpm to create an rpm package to distribute my python app on linux. When i install the rpm, the files are installed in...
3
by: duyanning | last post by:
I have written a pyhton script that will process data file in current working directory. My script is in an different directory to data file. When I debug this script using pdb within emacs, emacs...
4
by: Colin J. Williams | last post by:
1.I have both 2.5 and 2.6 but both appear, under Recent Projects, as pcbuild. It would be helpful if the Python Version could be indicated. 2.With 2.6, Python compiles and executes OK but...
0
by: cnivas | last post by:
Hi, I'm doing a small application in python using mac os x. Now, I want to insert an image in the web application. I have given the image path also... but it shows "?" this symbol.... If the...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.