Search code examples
python-3.5file-writingbz2

Python3: write string into .txt.bz2 file


I want to write the join result by two list into the txt.bz2 file(the file name is named by code, not exist at the beginning). like the following form in txt file.

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

But there is error. My code is following, please give me hints how to deal with it. Thanks!

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

error:

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

Solution

  • Open the file in text mode:

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

    More succinctly:

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