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

时间:2017-02-27 11:37:58

标签: python-3.5 file-writing bz2

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

2 个答案:

答案 0 :(得分:1)

使用文件bz2.BZ2File(path)打开bz2文件。

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

答案 1 :(得分: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())))