通过遍历输入的每个文件来制作zip的内存中副本 [英] Make in-memory copy of a zip by iterating over each file of the input

查看:79
本文介绍了通过遍历输入的每个文件来制作zip的内存中副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就目前所知,Python不允许修改存档文件.这就是为什么我想要

Python, as far as know, does not allow modification of an archived file. That is why I want to:

  1. 解压缩内存中的zip(zip_in).
  2. 遍历zip_in中的每个文件,并根据需要进行更改,然后将其复制到zip_out中.现在,我很高兴只复制一个文件.
  3. 保存zip_out.

我正在尝试zipfileio,但是没有运气.部分原因是我不确定所有工作原理以及哪个对象需要哪个输出.

I was experimenting with zipfile and io but no luck. Partially because I'm not sure how all that works and which object requires which output.

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

推荐答案

ZipFile.extract()需要文件名,而不是要写入的类似文件的对象.而是使用ZipFile.read(name)获取文件的内容.它返回字节字符串,因此可以很好地处理二进制文件.文本文件可能需要解码为unicode.

ZipFile.extract() expects a filename, not a file-like object to write to. Instead, use ZipFile.read(name) to get the contents of the file. It returns the byte string so will work fine with binary files. Text files may require decoding to unicode.

这篇关于通过遍历输入的每个文件来制作zip的内存中副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆