简体   繁体   中英

Python zip all files in directory script failed

I want to write a very simple script with python that will zip all file in a folder. This is what i have until now:

import os
import zipfile
zfName = 'simonsZip.zip'
foo = zipfile.ZipFile(zfName, 'w')
for dirname, dirnames, filenames in os.walk('.'):
    # print path to all filenames.
    for filename in filenames:
        print (os.path.join(dirname,filename))
        foo.write(os.path.join(dirname, filename))
    foo.close()

When i sudo python script.py the script runs, but never ends, while producing an enormous zip file.

Any ideas?

You're doing a recursion. since the zip you created is listed in the files. You're writing the zip inside the zip inside the zip inside the zip and so on.

this might become handy for you if you are running linux or osx .

from subprocess import call

zfName = 'simonsZip'
fnames = '*' #all files
call(["zip","-R", zfName, fnames])

this just zip all the files in the current directory recursively( -R ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM