2017-02-27 168 views
0

我想通過兩個列表將連接結果寫入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