11

Here is what I have:

import bz2

compressionLevel = 9
source_file = '/foo/bar.txt' #this file can be in a different format, like .csv or others...
destination_file = '/foo/bar.bz2'

tarbz2contents = bz2.compress(source_file, compressionLevel)
fh = open(destination_file, "wb")
fh.write(tarbz2contents)
fh.close()

I know first param of bz2.compress is a data, but it's the simple way that I found to clarify what I need.

And I know about BZ2File but, I cannot find any good example to use BZ2File.

Lucas
  • 1,514
  • 3
  • 16
  • 23

1 Answers1

15

The documentation for bz2.compress for says it takes data, not a file name.
Try replacing the line below:

tarbz2contents = bz2.compress(open(source_file, 'rb').read(), compressionLevel)

...or maybe :

with open(source_file, 'rb') as data:
    tarbz2contents = bz2.compress(data.read(), compressionLevel)
Gerrat
  • 28,863
  • 9
  • 73
  • 101
  • Great @Gerrat! the first option worked for me. Thanks! – Lucas Sep 21 '16 at 13:03
  • 1
    I do not think the second option is strictly correct. I think it should be `with open(source_file, 'rb') as data: tarbz2contents = bz2.compress(data.read(), compressionLevel)` – ngalstyan Mar 25 '18 at 22:20