通过遍历输入的每个文件在内存中复制zip文件

1 投票
1 回答
2010 浏览
提问于 2025-04-16 11:10

根据我所知道的,Python不允许直接修改一个压缩文件。这就是我想要做的事情:

  1. 把压缩文件解压到内存中(叫它zip_in)。
  2. 逐个查看zip_in里的每个文件,如果需要的话进行修改,然后把它复制到另一个压缩文件zip_out里。现在我只想简单地复制一个文件。
  3. 保存zip_out。

我在尝试使用zipfileio这两个模块,但没有成功。部分原因是我不太清楚这些模块是怎么工作的,以及每个对象需要什么样的输出。

有效的代码

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

1 个回答

2

ZipFile.extract() 这个方法需要一个文件名,而不是一个可以写入的文件对象。你应该使用 ZipFile.read(name) 来获取文件的内容。这个方法会返回字节字符串,所以对于二进制文件来说没问题。不过,对于文本文件,你可能需要把它解码成 Unicode 格式。

撰写回答