1

我想将两个列表的连接结果写入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'
4

2 回答 2

2

以文本模式打开文件:

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())))
于 2018-01-15T21:48:24.537 回答
1

您使用文件打开一个 bz2 文件bz2.BZ2File(path)

with bz2.BZ2File("data/result_small.txt.bz2", "rt") as bz_file:
    #...
于 2017-02-27T11:47:39.443 回答