在 Python 中压缩文件的更好方法(使用单个命令压缩整个目录)?
假设我有一个目录:/home/user/files/
。这个目录有一堆文件:
/home/user/files/
-- test.py
-- config.py
我想在 python 中使用 ZipFile 来压缩这个目录。我是否需要循环遍历目录并递归添加这些文件,或者是否可以传递目录名称,并且 ZipFile 类会自动添加其下的所有内容?
最后,我想要:
/home/user/files.zip (and inside my zip, I dont need to have a /files folder inside the zip:)
-- test.py
-- config.py
Possible Duplicate:
How do I zip the contents of a folder using python (version 2.5)?
Suppose I have a directory: /home/user/files/
. This dir has a bunch of files:
/home/user/files/
-- test.py
-- config.py
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?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请注意,这不包括空目录。如果需要这些,可以在网上找到解决方法;也许最好在我们最喜欢的归档程序中获取空目录的 ZipInfo 记录,以查看其中的内容。
硬编码文件/路径以消除我的代码的细节......
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.
Hardcoding file/path to get rid of specifics of my code...
您可以尝试使用 distutils 包:
You could try using the distutils package:
您也许还可以使用
zip
命令可在 Unix shell 中调用os.system
You might also be able to get away with using the
zip
command available in the Unix shell with a call toos.system
您可以使用
subprocess
模块:代码未经测试,假装仅在 unix 机器上运行,我不知道 Windows 是否有类似的命令行实用程序。
You could use
subprocess
module:The code is not tested and pretends to works just on unix machines, i don't know if windows has similar command line utilities.