all Python 3bz2term
bz2.BZ2File
files
A file object for reading and writing bzip2-compressed data in binary mode. It takes a file name or an already open file.
Syntax
f = bz2.BZ2File(filename, mode='r', *, compresslevel=9)
BZ2File handles bytes only: mode 'rt' or 'wt' gives ValueError — for text use bz2.open(), which wraps the file in a TextIOWrapper for you. Mode 'a' does not extend the existing stream but appends a new one; reading joins the streams transparently. Without closing it (with) the tail of the compressed data never reaches the disk.
Examples
import bz2
with bz2.BZ2File('log.bz2', 'w') as f:
f.write(b'first ')
with bz2.BZ2File('log.bz2', 'a') as f:
f.write(b'second')
with bz2.BZ2File('log.bz2') as f:
print(f.read()) # → b'first second'
import bz2
try:
bz2.BZ2File('x.bz2', 'wt')
except ValueError as e:
print(e) # → Invalid mode: 'wt'
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy