2017-10-14 3 views
0

現在、複数のテキスト行を含むテキストファイルを生成し、Python 2.7でメモリ内のZipFileに追加することについていくつかの問題があります。ZipFIleを開くときにStringIOオブジェクト、CRCエラーのリストを含むZipFileを生成する

以下のコードは、4つのテキストファイルを持つzipファイルを生成することができます。各ファイルには1行の単語があります。

"temp [0] .write( '最初のメモリ内の一時ファイル')というコードを複数行の文字列に変更すると、生成されたzipファイルにcrcエラーが発生します。

私は文字列エスケープを試みましたが、失敗しました。

MultipleLine対応のテキストファイルでZipFileを生成するにはどうすればよいですか?

ありがとうございます。

# coding: utf-8 

import StringIO 
import zipfile 

# This is where my zip will be written 
buff = StringIO.StringIO() 
# This is my zip file 
zip_archive = zipfile.ZipFile(buff, mode='w') 

temp = [] 
for i in range(4): 
    # One 'memory file' for each file 
    # I want in my zip archive 
    temp.append(StringIO.StringIO()) 

# Writing something to the files, to be able to 
# distinguish them 
temp[0].write('first in-memory temp file') 
temp[1].write('second in-memory temp file') 
temp[2].write('third in-memory temp file') 
temp[3].write('fourth in-memory temp file') 

for i in range(4): 
    # The zipfile module provide the 'writestr' method. 
    # First argument is the name you want for the file 
    # inside your zip, the second argument is the content 
    # of the file, in string format. StringIO provides 
    # you with the 'getvalue' method to give you the full 
    # content as a string 
    zip_archive.writestr('temp'+str(i)+'.txt', 
         temp[i].getvalue()) 

# Here you finish editing your zip. Now all the information is 
# in your buff StringIO object 
zip_archive.close() 

# You can visualize the structure of the zip with this command 
print zip_archive.printdir() 

# You can also save the file to disk to check if the method works 
with open('test.zip', 'w') as f: 
    f.write(buff.getvalue()) 

答えて

1

あなたはWindowsを使用していると思いますか? Windowsで\r\nあるシーケンスを終了するネイティブラインに新しい行(「\ n」を)変換テキストモード(デフォルト)Pythonでは

with open('test.zip', 'wb') as f: 
    f.write(buff.getvalue()) 

すなわち、バイナリモードでは、出力zipファイルを開いてみてください。これにより、CRCは、 StringIOバッファ内のデータを使用して計算されるためCRCが失敗することになりますが、テキストモードファイルに書き込まれるときにデータが変更されます( \n\r\nに変換されます)。

関連する問題