电脑在玩我,我知道!
我正在 Python 中创建一个 zip 文件夹。单个文件在内存中生成,然后将整个文件压缩并保存到文件中。我可以在 zip 中添加 9 个文件。我可以在 zip 中添加 11 个文件。但是 10 个,不,不是 10 个文件。zip 文件已保存到我的计算机上,但我无法打开它;Windows 说压缩的压缩文件夹无效。
我使用下面的代码,这是我从另一个 stackoverflow 问题中得到的。它附加 10 个文件并保存压缩文件夹。当我单击该文件夹时,我无法提取它。但是,删除其中一个 appends() 就可以了。或者,添加另一个追加,它的工作原理!
我在这里想念什么?我怎样才能每次都完成这项工作?
imz = InMemoryZip()
imz.append("1a.txt", "a").append("2a.txt", "a").append("3a.txt", "a").append("4a.txt", "a").append("5a.txt", "a").append("6a.txt", "a").append("7a.txt", "a").append("8a.txt", "a").append("9a.txt", "a").append("10a.txt", "a")
imz.writetofile("C:/path/test.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)
# 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()