1
zip = zipfile.ZipFile(destination+ff_name,"w")
            zip.write(source)
            zip.close()

Above is the code that I am using, and here "source" is the path of the directory. But when I run this code it just zips the source folder and not the files and and folders contained in it. I want it to compress the source folder recursively. Using tarfile module I can do this without passing any additional information.

Dharman
  • 30,962
  • 25
  • 85
  • 135
hsinxh
  • 1,865
  • 6
  • 21
  • 25

3 Answers3

2

The standard os.path.walk() function will likely be of great use for this.

Alternatively, reading the tarfile module to see how it does its work will certainly be of benefit. Indeed, looking at how pieces of the standard library were written was an invaluable part of my learning Python.

msw
  • 42,753
  • 9
  • 87
  • 112
  • I did look at your pastebin. It is pretty good work for a novice, and you should be pleased. However, there are many things that you accomplished the hard way so I point you toward resources that should help you on your journey: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers – msw Dec 26 '10 at 07:14
2

I haven't tested this exactly, but it's something similar to what I use.

zip = zipfile.ZipFile(destination+ff_name, 'w', zipfile.ZIP_DEFLATED)
rootlen = len(source) + 1
for base, dirs, files in os.walk(source):
    for file in files:
        fn = os.path.join(base, file)
        zip.write(fn, fn[rootlen:])

This example is from here:

http://bitbucket.org/jgrigonis/mathfacts/src/ff57afdf07a1/setupmac.py

jgritty
  • 11,660
  • 3
  • 38
  • 60
1

I'd like to add a "new" python 2.7 feature to this topic: ZipFile can be used as a context manager and therefore you can do things like this:

        with zipfile.ZipFile(my_file, 'w') as myzip:
            rootlen = len(xxx) #use the sub-part of path which you want to keep in your zip file 
            for base, dirs, files in os.walk(pfad):
                for ifile in files:
                    fn = os.path.join(base, ifile)
                    myzip.write(fn, fn[rootlen:])
OBu
  • 4,977
  • 3
  • 29
  • 45