Python3: 将字符串写入.txt.bz2 文件

Python3: write string into .txt.bz2 file

我想把两个list的join结果写到txt.bz2文件中(文件名由代码命名,开头不存在)。就像txt文件中的以下表格。

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'

您使用 bz2.BZ2File(path).

文件打开了一个 bz2 文件
with bz2.BZ2File("data/result_small.txt.bz2", "rt") as bz_file:
    #...

以文本模式打开文件:

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())))