【问题标题】:Better way to zip files in Python (zip a whole directory with a single command)? [duplicate]在 Python 中压缩文件的更好方法(使用单个命令压缩整个目录)? [复制]
【发布时间】:2010-08-31 18:36:51
【问题描述】:

可能重复:
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

【问题讨论】:

  • 因为 os.walk 产生了目录的全部内容——为你做递归——它看起来像是一个微不足道的循环。你想优化什么?代码行?我不明白怎么做。时间?不可能——Zip 需要时间。你有什么问题?
  • 我只想压缩一个可能包含空文件夹的文件夹,而不需要为我的 Linux 机器使用 zip 实用程序和 subprocess 模块通过单个命令执行的操作编写一堆行。跨度>

标签: python zip


【解决方案1】:

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

【讨论】:

  • 在 python 3 中,pathlib 模块使这更容易,像这样使用Path(<your_path>).rglob('*') 将所有文件添加到 ZipFile 对象:for _file in Path(path).rglob('*'): zip.write(str(_file))
【解决方案2】:

您可以尝试使用 distutils 包:

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

【讨论】:

    【解决方案3】:

    您还可以通过调用os.system 来使用Unix shell 中可用的zip 命令来摆脱困境

    【讨论】:

      【解决方案4】:

      您可以使用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是否有类似的命令行实用程序。

      【讨论】:

      • 我已经在脚本的另一部分使用了子进程,这就是我要找的!我没想过使用 *nixes 机器上的 zip,谢谢!
      猜你喜欢
      • 2021-03-22
      • 2011-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      相关资源
      最近更新 更多