Python Glossary Русский

Python 3.3+bz2function

bz2.open()

files

Opens a bzip2 file in binary or text mode — the counterpart of the built-in open() for compressed files.

Syntax

f = bz2.open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)

The default mode is 'rb', not 'r': without 't', read() returns bytes. In text mode ('rt', 'wt') pass encoding, otherwise the locale encoding is used and a file with Cyrillic text reads differently on another machine. encoding and newline are forbidden in binary mode — ValueError.

Examples

import bz2
with bz2.open('notes.txt.bz2', 'wt', encoding='utf-8') as f:
    f.write('привет\nмир\n')
with bz2.open('notes.txt.bz2', 'rt', encoding='utf-8') as f:
    print(f.readlines())  # → ['привет\n', 'мир\n']
with bz2.open('notes.txt.bz2') as f:
    print(type(f.read()).__name__)  # → bytes

See also

Open in the full glossarydocs.python.orgReport an inaccuracy