Python教程

python将内存数据压缩成zip

本文主要是介绍python将内存数据压缩成zip,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
# !user/bin/env python3
# -*-coding : utf-8 -*-

import zipfile
from io import BytesIO
import os


class InMemoryZIP(object):
    def __init__(self):
        # create the in-memory file-like object
        self.in_memory_zip = BytesIO()

    def append(self, filename_in_zip, file_contents):
        """ Appends a file with name filename_in_zip \
        and contents of file_contents to the in-memory zip.
        """
        # create a handle to the in-memory zip in append mode\
        if not isinstance(file_contents, bytes):
            file_contents = bytes(str(file_contents), encoding='utf-8')

        zf = zipfile.ZipFile(self.in_memory_zip, 'a',
                             zipfile.ZIP_DEFLATED, False)

        # write the file to the in-memory zip
        zf.writestr(filename_in_zip, file_contents)

        # mark the files as having been created on Windows
        # so that Unix permissions are not inferred as 0000
        for zfile in zf.filelist:
            zfile.create_system = 0
        return self

    def appendfile(self, file_path, file_name=None):
        """ Read a file with path file_path \
        and append to in-memory zip with name file_name.
        """
        if file_name is None:
            file_name = os.path.split(file_path)[1]

        f = open(file_path, 'rb')
        file_contents = f.read()
        self.append(file_name, file_contents)
        f.close()
        return self

    def read(self):
        """ Returns a string with the contents of the in-memory zip.
        """
        self.in_memory_zip.seek(0)
        return self.in_memory_zip.read()

    def writetofile(self, filename):
        """
        Write the in-memory zip to a file
        """
        f = open(filename, 'wb')
        f.write(self.read())
        f.close()


if __name__ == '__main__':

     contens = 'xxxxxxxxx'  # 内存数据
     imz = InMemoryZIP()
     imz.append('test.txt', contens)
     imz.writetofile('test.zip')
   


这篇关于python将内存数据压缩成zip的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!