据了解,Python 不允许修改存档文件。这就是为什么我想:
- 在内存中解压缩 zip (zip_in)。
- 检查 zip_in 中的每个文件,并根据需要进行更改,然后将其复制到 zip_out。现在我很高兴只制作文件的副本。
- 保存 zip_out。
我正在尝试使用 zipfile
和 io
但没有运气。部分原因是我不确定这一切是如何工作的以及哪个对象需要哪个输出。
工作代码
import os
import io
import codecs
import zipfile
# Make in-memory copy of a zip file
# by iterating over each file in zip_in
# archive.
#
# Check if a file is text, and in that case
# open it with codecs.
zip_in = zipfile.ZipFile(f, mode='a')
zip_out = zipfile.ZipFile(fn, mode='w')
for i in zip_in.filelist:
if os.path.splitext(i.filename)[1] in ('.xml', '.txt'):
c = zip_in.open(i.filename)
c = codecs.EncodedFile(c, 'utf-8', 'utf-8').read()
c = c.decode('utf-8')
else:
c = zip_in.read(i.filename)
zip_out.writestr(i.filename, c)
zip_out.close()
旧示例,有问题
# Make in-memory copy of a zip file
# by iterating over each file in zip_in
# archive.
#
# This code below does not work properly.
zip_in = zipfile.ZipFile(f, mode='a')
zip_out = zipfile.ZipFile(fn, mode='w')
for i in zip_in.filelist:
bc = io.StringIO() # what about binary files?
zip_in.extract(i.filename, bc)
zip_out.writestr(i.filename, bc.read())
zip_out.close()
错误是TypeError:'_io.StringIO'对象不可订阅
最佳答案
ZipFile.extract()
需要一个文件名,而不是要写入的类似文件的对象。相反,使用 ZipFile.read(name) 来获取文件的内容。它返回字节字符串,因此可以很好地处理二进制文件。文本文件可能需要解码为 unicode。
关于python - 通过迭代输入的每个文件来制作 zip 的内存副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4890860/