How to compress a file with bzip2 in Python?
<p>Here is what I have:</p>

<pre><code>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()
</code></pre>

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

<p>And I know about BZ2File but, I cannot find any good example to use BZ2File.</p>

<p>The <a href="https://docs.python.org/2/library/bz2.html#bz2.compress" rel="nofollow">documentation for bz2.compress</a> for says it takes data, not a file name.<br>
Try replacing the line below:</p>

<pre><code>tarbz2contents = bz2.compress(open(source_file, 'rb').read(), compressionLevel)
</code></pre>

<p>...or maybe :</p>

<pre><code>with open(source_file, 'rb') as data:
    tarbz2contents = bz2.compress(data, compressionLevel)
</code></pre>

python compression bzip2