【发布时间】: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 模块通过单个命令执行的操作编写一堆行。跨度>