【问题标题】:Python, how to create in-memory zip file whose files contained in it could have any format (.txt, .jpg, etc.)Python,如何创建内存中的 zip 文件,其中包含的文件可以是任何格式(.txt、.jpg 等)
【发布时间】:2014-12-19 01:08:17
【问题描述】:

我正在尝试创建一个在内存中创建 .zip 的类,其内容可以是任何格式的文件,以便以后使用。我找到了有用的代码并构建了这个类:

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)

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

# Run a test
if __name__ == "__main__":
    imz = InMemoryZip()
    imz.append("samples/main.cpp", "//Hello code").append("samples/bee.jpg", open('bee.jpg', 'rb').read())
    imz.writetofile("test.zip")

如果我只尝试压缩文本文件,它工作得很好,但是我得到了带有 .jpg、.png、... 的损坏的 zip 文件几乎和我喜欢的 example1example2 一样

以下code 有效(但不在内存中):

import zipfile
import glob, os

# open the zip file for writing, and write stuff to it

file = zipfile.ZipFile("test.zip", "w")

for name in glob.glob("samples/*"):
    file.write(name, os.path.basename(name), zipfile.ZIP_DEFLATED)

file.close()

# open the file again, to see what's in it

file = zipfile.ZipFile("test.zip", "r")
for info in file.infolist():
    print info.filename, info.date_time, info.file_size, info.compress_size

那么,我应该将 BytesIO 用于图像、可执行文件……吗?我必须辨别文件格式吗?

注意:我的操作系统是 Windows 8.1 x64

【问题讨论】:

  • 我对其进行了测试,它对我有用:还有别的东西吗?
  • 你试过BytesIO(适用于所有类型)吗?
  • @MicheleD'Amico,您是否尝试在压缩后打开 *.png 或 *.jpg 并且它有效?看到原图了吗?
  • @wwii 是的,我做了,但没用
  • @fenix688 是的,我做到了,它有效。但我刚才注意到您使用的是 Windows 操作系统,也许我的操作系统运行良好:我使用的是 Linux :)

标签: windows python-2.7 zipfile in-memory stringio


【解决方案1】:

Windows 操作系统?在这种情况下,您需要更改在测试代码中打开文件的方式(注意"b"):

f = file(filename, "wb")

压缩文件包含基本上随机的字节组合。其中一些字节最终必然是\n,如果你不以二进制模式打开文件,它们将被转换为\r\n。这会损坏文件。

它恰好适用于文本文件只是一个巧合,可能是因为它们很小。

【讨论】:

  • 非常感谢!有用!我没有意识到将其修改为“wb”! :(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
  • 1970-01-01
  • 2021-09-17
相关资源
最近更新 更多