python快速生成目录结构_python生成zip压缩文件目录结构,,下面python代码片段

python生成zip压缩文件目录结构,,下面python代码片段

下面python代码片段用来生成zip压缩文件中的目录结构,支持嵌套压缩。import zipfileimport osimport cStringIOdef zipwalk(zfilename): """Zip file tree generator. For each file entry in a zip archive, this yields a two tuple of the zip information and the data of the file as a StringIO object. zipinfo, filedata zipinfo is an instance of zipfile.ZipInfo class which gives information of the file contained in the zip archive. filedata is a StringIO instance representing the actual file data. If the file again a zip file, the generator extracts the contents of the zip file and walks them. Inspired by os.walk . """ tempdir=os.environ.get('TEMP',os.environ.get('TMP',os.environ.get('TMPDIR','/tmp'))) try: z=zipfile.ZipFile(zfilename,'r') for info in z.infolist(): fname = info.filename data = z.read(fname) extn = (os.path.splitext(fname)[1]).lower() if extn=='.zip': checkz=False tmpfpath = os.path.join(tempdir,os.path.basename(fname)) try: open(tmpfpath,'w+b').write(data) except (IOError, OSError),e: print e if zipfile.is_zipfile(tmpfpath): checkz=True if checkz: try: for x in zipwalk(tmpfpath): yield x except Exception, e: raise try: os.remove(tmpfpath) except: pass else: yield (info, cStringIO.StringIO(data)) except RuntimeError, e: print 'Runtime Error' except zipfile.error, e: raiseif __name__=="__main__": import sys for i,d in zipwalk(sys.argv[1]): print i.filename

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值