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
相关内容
- python里的签名方法hmac,python签名hmac,>>> import h
- 正则表达式断言学习,正则表达式断言,关于前瞻断言,
- import python 配置文件,importpython,这段代码演示使用imp
- Python 获取目录下的文件列表与内容,python获取,下面的
- Python使用socket类获取服务器IP地址,pythonsocket,Python 获取
- python源代码语法高亮输出,python源代码高亮,## {{{ http
- unix subprocess wrapper,subprocesswrapper,I have used
- Python+MongDB实现短链接,pythonmongdb实现,实现任意数制变
- Automatic ref-count management in C++ using a smart ptr,ref-countpt
- python判断文件和文件夹是否存在,python判断,python判断文
评论关闭