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

Som*_*DOS 8 python zip

可能重复:
如何使用python(版本2.5)压缩文件夹的内容?

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

/home/user/files/
  -- test.py
  -- config.py
Run Code Online (Sandbox Code Playgroud)

我想ZipFile在python中使用zip目录.我是否需要遍历目录并递归添加这些文件,或者是否可以传递目录名称,ZipFile类会自动添加其下的所有内容?

最后,我想:

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

das*_*ang 23

请注意,这不包括空目录.如果需要,可以在网上找到解决方法; 可能最好在我们最喜欢的归档程序中获取空目录的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:])
Run Code Online (Sandbox Code Playgroud)


bos*_*acs 6

您可以尝试使用distutils包:

distutils.archive_util.make_zipfile(base_name, base_dir[, verbose=0, dry_run=0])
Run Code Online (Sandbox Code Playgroud)


mg.*_*mg. 1

您可以使用subprocess模块:

import subprocess

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

该代码未经测试,假装仅在 unix 机器上运行,我不知道 Windows 是否有类似的命令行实用程序。