2011-02-03 46 views
1

的Python中的每个文件使内存拉链的副本,只要知道了,不允许归档文件的修改。这就是为什么我想:通过iterrating在输入

  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

回答

2

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

+0

谢谢,马特。结合`编解码器'和你的提示,我解决了这个问题。 – marw 2011-02-08 19:16:52