在 Python 中压缩文件的更好方法(使用单个命令压缩整个目录)? [英] Better way to zip files in Python (zip a whole directory with a single command)?

查看:34
本文介绍了在 Python 中压缩文件的更好方法(使用单个命令压缩整个目录)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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 possible do pass the directory name and the ZipFile class automatically adds everything beneath it?

最后,我想:

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

推荐答案

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

The code is not tested and pretends to works just on unix machines, i don't know if windows has similar command line utilities.

这篇关于在 Python 中压缩文件的更好方法(使用单个命令压缩整个目录)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆