自定义python的类InMemoryZip,可以在内存压缩文件为zip

2022-05-03 00:00:00 内存 自定义 压缩文件

自定义python的类InMemoryZip,可以在内存压缩文件为zip,也可以对文件进行解压缩,同时还可以通过网络对文件进行压缩后进行高速传输

"""
皮蛋编程(https://www.pidancode.com)
创建日期:2022/3/29
功能描述:自定义python的类InMemoryZip,可以在内存压缩文件为zip
"""

import io
import os
import zipfile
class InMemoryZip:
    """ Basic idea behind was to be able to transfer single files or
        or a folder (with sub folders) as zipped memory via communication
        to another machine. """
    def __init__(self, data=None):
        """ creating an in memory file (zip archive) """
        self.inMemory = io.BytesIO()
        if data:
            self.setData(data)
    def getData(self):
        """ retrieving the whole file as buffer """
        self.inMemory.seek(0)
        return self.inMemory.read()
    def setData(self, data):
        """ creating new in memory file wit new content """
        self.inMemory = io.BytesIO()
        self.inMemory.write(data)
    def append(self, pathAndFileName):
        """ adding a file or a path (recursive) to the zip archive in memory """
        zf = zipfile.ZipFile(self.inMemory, "a", zipfile.ZIP_DEFLATED, False)
        if os.path.isfile(pathAndFileName):
            zf.write(pathAndFileName)
        else:
            path = pathAndFileName
            for root, folders, files in os.walk(path):
                for file in files:
                    fullName = os.path.join(root, file)
                    zf.write(fullName)
    def saveAs(self, pathAndFileName):
        """ does save the in memory zip archive to a file """
        file = open(pathAndFileName, "wb")
        file.write(self.getData())
        file.close()
    def readFrom(self, pathAndFileName):
        """ reading a file expected to be a ZIP file """
        self.setData(open(pathAndFileName, "rb").read())
    def extractAllAt(self, path):
        """ does extract all files in memory below given path;
            the underlying zipfile module is clever enough to
            create the necessary path if not existing """
        zf = zipfile.ZipFile(self.inMemory)
        zf.extractall(path)
    def listContent(self):
        """ getting list of zip files entries (ZipInfo instances) """
        zf = zipfile.ZipFile(self.inMemory)
        return zf.infolist()
def test():
    zm = InMemoryZip()
    zm.append(".")
    zm.saveAs("InMemoryZip_test.zip")
    zm2 = InMemoryZip(zm.getData())
    zm2.extractAllAt("./tmp")
    zm3 = InMemoryZip()
    zm3.readFrom("InMemoryZip_test.zip")
    for entry in zm3.listContent():
        print(entry.filename)
if __name__ == "__main__":
    test()

以上代码在python3.9环境下测试通过

相关文章