Better way to zip files in Python (zip a whole directory with a single command)? [duplicate]
Possible Duplicate:
How do I zip the contents of a folder using python (version 2.5)?
Suppose I have a directory: /home/user/files/
. This dir has a bunch of files:
/home/user/files/
-- test.py
-- config.py
I want to zip this directory using ZipFile
in python. Do I need to loop through the directory and add these files recursively, or is it po开发者_JAVA百科ssible do pass the directory name and the ZipFile class automatically adds everything beneath it?
In the end, I would like to have:
/home/user/files.zip (and inside my zip, I dont need to have a /files folder inside the zip:)
-- test.py
-- config.py
Note that this doesn't include empty directories. If those are required there are workarounds available on the web; probably best to get the ZipInfo record for empty directories in our favorite archiving programs to see what's in them.
Hardcoding file/path to get rid of specifics of my code...
target_dir = '/tmp/zip_me_up'
zip = zipfile.ZipFile('/tmp/example.zip', 'w', zipfile.ZIP_DEFLATED)
rootlen = len(target_dir) + 1
for base, dirs, files in os.walk(target_dir):
for file in files:
fn = os.path.join(base, file)
zip.write(fn, fn[rootlen:])
You could try using the distutils package:
distutils.archive_util.make_zipfile(base_name, base_dir[, verbose=0, dry_run=0])
You might also be able to get away with using the zip
command available in the Unix shell with a call to os.system
You could use subprocess
module:
import subprocess
PIPE = subprocess.PIPE
pd = subprocess.Popen(['/usr/bin/zip', '-r', 'files', 'files'],
stdout=PIPE, stderr=PIPE)
stdout, stderr = pd.communicate()
The code is not tested and pretends to works just on unix machines, i don't know if windows has similar command line utilities.
精彩评论