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')
   


上一篇:动态规划学习(打家劫舍一)


下一篇:RuntimeError: CUDA out of memory. Tried to allocate 170.00 MiB (GPU 0; 3.82 GiB total capacity; 1.94