hsinxh
hsinxh

Reputation: 1875

create zip of complete directory using zipfile python module

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.

Upvotes: 1

Views: 5435

Answers (3)

OBu
OBu

Reputation: 5167

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:])

Upvotes: 1

jgritty
jgritty

Reputation: 11915

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

Upvotes: 2

msw
msw

Reputation: 43487

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.

Upvotes: 2

Related Questions