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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3612094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:56:46  来源:igfitidea点击:

Better way to zip files in Python (zip a whole directory with a single command)?

pythonzip

提问by Somebody still uses you MS-DOS

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

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

Suppose I have a directory: /home/user/files/. This dir has a bunch of files:

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

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

I want to zip this directory using ZipFilein python. Do I need to loop through the directory and add these files recursively, or is it possible do pass the directory name and the ZipFile class automatically adds everything beneath it?

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

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

采纳答案by mg.

You could use subprocessmodule:

您可以使用subprocess模块:

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.

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

回答by bosmacs

You could try using the distutils package:

您可以尝试使用 distutils 包:

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

回答by inspectorG4dget

You might also be able to get away with using the zipcommand available in the Unix shell with a call to os.system

您也可以zip通过调用 Unix shell 中可用的命令来逃避os.system

回答by dash-tom-bang

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.

请注意,这不包括空目录。如果需要这些,网络上有可用的解决方法;可能最好在我们最喜欢的归档程序中获取空目录的 ZipInfo 记录,以查看其中的内容。

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