据我所知,Python不允许修改存档文件。这就是我想要的原因:
我正在试验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' object is not subscriptable
答案 0 :(得分:2)
ZipFile.extract()
需要一个文件名,而不是一个类似文件的对象。而是使用ZipFile.read(name)
来获取文件的内容。它返回字节字符串,因此可以正常使用二进制文件。文本文件可能需要解码才能解码。