Python: 使用zipfile+io模块在内存中进行zip操作

#!/usr/bin/env python
#coding=utf-8
'''
    版权所有 (c) 2014 yao_yu (http://blog.csdn.net/yao_yu_126)
    本代码采用MIT许可
    使用io.BytesIO()在内存中压缩,解压缩zip文件
    2014-04-30      yaoyu 创建
'''

import zipfile
import os
import io
from base64     import standard_b64decode
try:
    from .yy_file       import *
except:
    from yy_file        import *

__all__ = ['yy_zip_files2buffer', 'yy_zip_files', 'yy_unzip_buffer2files', 'yy_unzip_base64zipfile']

def yy_zip_files2buffer(files):
    '''文件压缩到内存中'''
    buffer = io.BytesIO()
    zfile = zipfile.ZipFile(buffer, 'w', zipfile.ZIP_DEFLATED, allowZip64=False)
    for i in files:
        if os.path.isfile(i):
            zfile.write(i, os.path.basename(i))
    zfile.close()
    buffer.seek(0)
    return buffer

def yy_zip_files(zipfilename, files):
    '''压缩文件列表到zip文件'''
    yy_file_write_bytes(zipfilename, yy_zip_files2buffer(files).read())

def yy_unzip_buffer2files(buffer):
    '''从内存压缩文件中读取文件信息'''
    zfile = zipfile.ZipFile(buffer, 'r')
    files = []
    for i in zfile.filelist:
        files.append((i.filename, zfile.read(i.filename)))
    return files

def yy_unzip_base64zipfile(szFile):
    '''从base64压缩的zip文件中读取第一个文件二进制内容'''
    bytescontent = yy_file_read_bytes(szFile)
    for (find, replace) in ((b'
', b'\n'),
                            (b'
', b'\r')):
        if find in bytescontent:
            bytescontent = bytescontent.replace(find, replace)
    filebytes = standard_b64decode(bytescontent)
    fileinfos = yy_unzip_buffer2files(io.BytesIO(filebytes))
    if fileinfos:
        return fileinfos[0][1]

if __name__ == '__main__':
    sourcedir = '/Volumes/Data/Document/百度云同步盘/Develop/Python/Calculator'
    files = (os.path.join(sourcedir, i) for i in os.listdir(sourcedir))
    yy_zip_files(os.path.join(sourcedir, 'dist', 'r.zip'), files)
    #print(yy_unzip_buffer2files(yy_zip_files2buffer(files)))

    
    filename = '/Volumes/Data/Download/aaa'
    filebytes = yy_unzip_base64zipfile(filename)
    yy_file_write_bytes(filename + '.xls', filebytes)

 

posted @ 2014-04-30 09:18  一花一世界,一叶一乾坤  阅读(2158)  评论(0编辑  收藏  举报