国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python使用內存zipfile對象在內存中打包文件示例

2019-11-25 18:25:37
字體:
來源:轉載
供稿:網友

復制代碼 代碼如下:

import zipfile
import StringIO

class InMemoryZip(object):
    def __init__(self):
        # Create the in-memory file-like object
        self.in_memory_zip = StringIO.StringIO()

    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.'''
        # Get a handle to the in-memory zip in append mode
        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 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):
        '''Writes the in-memory zip to a file.'''
        f = file(filename, "w")
        f.write(self.read())
        f.close()

if __name__ == "__main__":
    # Run a test
    imz = InMemoryZip()
    imz.append("test.txt", "Another test").append("test2.txt", "Still another")
    imz.writetofile("test.zip")

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 大宁县| 伽师县| 中方县| 隆子县| 象山县| 昌江| 玉龙| 抚顺市| 西华县| 康平县| 南通市| 昆明市| 武城县| 永城市| 阿图什市| 三明市| 和林格尔县| 尉犁县| 嘉黎县| 苍梧县| 鄂托克前旗| 彰化县| 漳平市| 若羌县| 建昌县| 连平县| 普定县| 巴林左旗| 开江县| 皋兰县| 墨竹工卡县| 罗山县| 天台县| 宁蒗| 淳化县| 临猗县| 宜章县| 措美县| 通化县| 太和县| 分宜县|