【发布时间】: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 文件几乎和我喜欢的 example1 或 example2 一样
以下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