如何使用python(版本2.5)压缩文件夹的内容? [英] How do I zip the contents of a folder using python (version 2.5)?
本文介绍了如何使用python(版本2.5)压缩文件夹的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这可能吗?
我该怎么做?
解决方案
改编版本的脚本是:
#!/ usr / bin / env python
from __future__ import with_statement
from contextlib import close
from zipfile导入ZipFile,ZIP_DEFLATED
import os
def zipdir(basedir,archivename):
assert os.path.isdir(basedir)
with closing(ZipFile(archivename, w,ZIP_DEFLATED))为z:
为root,dirs,os.walk(basedir)中的文件:
#NOTE:忽略空目录
为文件中的fn:
absfn = os.path.join(root,fn)
zfn = absfn [len(basedir)+ len(os.sep):] #XXX:相对路径
z.write(absfn,zfn )
如果__name__ =='__main__':
import sys
basedir = sys.argv [1]
archiv ename = sys.argv [2]
zipdir(basedir,archivename)
示例: / p>
C:\zipdir> python -mzipdir c:\tmp\test test.zip
它创建'C:\zipdir\test.zip'
存档与'c:\tmp\test'
目录的内容。
Once I have all the files I require in a particular folder, I would like my python script to zip the folder contents.
Is this possible?
And how could I go about doing it?
解决方案
Adapted version of the script is:
#!/usr/bin/env python
from __future__ import with_statement
from contextlib import closing
from zipfile import ZipFile, ZIP_DEFLATED
import os
def zipdir(basedir, archivename):
assert os.path.isdir(basedir)
with closing(ZipFile(archivename, "w", ZIP_DEFLATED)) as z:
for root, dirs, files in os.walk(basedir):
#NOTE: ignore empty directories
for fn in files:
absfn = os.path.join(root, fn)
zfn = absfn[len(basedir)+len(os.sep):] #XXX: relative path
z.write(absfn, zfn)
if __name__ == '__main__':
import sys
basedir = sys.argv[1]
archivename = sys.argv[2]
zipdir(basedir, archivename)
Example:
C:\zipdir> python -mzipdir c:\tmp\test test.zip
It creates 'C:\zipdir\test.zip'
archive with the contents of the 'c:\tmp\test'
directory.
这篇关于如何使用python(版本2.5)压缩文件夹的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文