python将内存数据压缩成zip
2021/9/18 7:07:47
本文主要是介绍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的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04Python外包有哪些常见的主要库-icode9专业技术文章分享
- 2024-10-02基于深度学习的钢铁缺陷检测系统(yolov8、注意力机制、PyQt5界面、Python)
- 2024-10-01怎么用python搭建一个系统-icode9专业技术文章分享
- 2024-09-30Python基础入门教程
- 2024-09-30获取参数学习:Python中的基础教程
- 2024-09-30Python编程基础详解
- 2024-09-29点击加载学习:Python编程基础教程
- 2024-09-29数据科学五大Python前端库:第二部分
- 2024-09-27使用python 将ETH账户的资产打散
- 2024-09-26Python编程基础