2017-02-27 30 views
0

2つのリストで結合結果をtxt.bz2ファイルに書きたい(ファイル名はコードで指定され、先頭には存在しない)。 txtファイルには次のような形式があります。Python3:文字列を.txt.bz2ファイルに書き込む

1 a,b,c 
0 d,f,g 
....... 

しかし、エラーがあります。私のコードは次のとおりです。どうすれば対処するのかのヒントを教えてください。ありがとう!

輸入BZ2

x = ['a b c', 'd f g', 'h i k', 'k j l'] 
y = [1, 0, 0, 1] 

with bz2.BZ2File("data/result_small.txt.bz2", "w") as bz_file: 
    for i in range(len(y)): 
     m = ','.join(x[i].split(' ')) 
     n = str(y[i])+'\t'+m 
     bz_file.write(n) 

エラー:

compressed = self._compressor.compress(data) 
TypeError: a bytes-like object is required, not 'str' 

答えて

0

オープンテキストモードでファイル:より簡潔

import bz2 

x = ['a b c', 'd f g', 'h i k', 'k j l'] 
y = [1, 0, 0, 1] 

with bz2.open("data/result_small.txt.bz2", "wt") as bz_file: 
    for i in range(len(y)): 
     m = ','.join(x[i].split(' ')) 
     n = str(y[i]) + '\t' + m 
     bz_file.write(n + '\n') 

import bz2 

x = ['a b c', 'd f g', 'h i k', 'k j l'] 
y = [1, 0, 0, 1] 

with bz2.open("data/result_small.txt.bz2", "wt") as bz_file: 
    for a, b in zip(x, y): 
     bz_file.write('{}\t{}\n'.format(b, ','.join(a.split()))) 
1

あなたはファイルbz2.BZ2File(path)を使って、BZ2ファイルを開きます。

with bz2.BZ2File("data/result_small.txt.bz2", "rt") as bz_file: 
    #... 
+0

が、エラーがあります:ValueErrorを送出し( "無効なモード:%R" %(モード) ) ValueError:無効なモード: 'rt' – tktktk0711

関連する問題