用Python压缩文件的更好方法(用一个命令压缩整个目录)?

2024-04-23 23:45:14 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
How do I zip the contents of a folder using python (version 2.5)?

假设我有一个目录:/home/user/files/。这个目录有一堆文件:

/home/user/files/
  -- test.py
  -- config.py

我想用python中的ZipFile压缩这个目录。我是否需要loop through the directory and add these files recursively,或者是否有可能传递目录名,并且ZipFile类会自动添加目录下的所有内容?

最后,我希望:

/home/user/files.zip (and inside my zip, I dont need to have a /files folder inside the zip:)
  -- test.py
  -- config.py

Tags: andthepytest目录confighomefiles
3条回答

您可以尝试使用distutils包:

distutils.archive_util.make_zipfile(base_name, base_dir[, verbose=0, dry_run=0])

注意,这不包括空目录。如果需要的话,可以在web上找到解决方法;最好是在我们最喜欢的归档程序中获取空目录的ZipInfo记录,查看其中的内容。

硬编码文件/路径,以摆脱我的代码细节。。。

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

您可以使用subprocess模块:

import subprocess

PIPE = subprocess.PIPE
pd = subprocess.Popen(['/usr/bin/zip', '-r', 'files', 'files'],
                      stdout=PIPE, stderr=PIPE)
stdout, stderr = pd.communicate()

这些代码没有经过测试,只是假装在unix机器上工作,我不知道windows是否有类似的命令行实用程序。

相关问题 更多 >