Python Glossary Русский

all Python 3gzipfunction

gzip.open()

gzip files

Opens a .gz file for reading or writing; binary mode works with bytes, 'rt'/'wt' with text.

Syntax

gzip.open(filename, mode='rb', compresslevel=6, encoding=None, errors=None, newline=None)

The default mode is 'rb', not 'r' as with open(): read() returns bytes, and string operations fail. For text, pass the mode explicitly — 'rt' or 'wt' — together with an encoding, or the default encoding is used (the locale encoding before 3.15). 'w' is binary too: writing a str raises TypeError. A file that is not gzip is detected not by open() but on the first read, as gzip.BadGzipFile. Since 3.15 the default compression level is 6, not 9: compression is faster and the archive slightly larger; pass compresslevel=9 explicitly to keep the old size.

Examples

import gzip
with gzip.open('log.txt.gz', 'wt', encoding='utf-8') as f:
    f.write('строка лога\n')
with gzip.open('log.txt.gz') as f:
    print(type(f.read()).__name__)  # → bytes — по умолчанию 'rb'
with gzip.open('log.txt.gz', 'rt', encoding='utf-8') as f:
    print(f.read().strip())  # → строка лога
import gzip
try:
    with gzip.open('data.gz', 'w') as f:
        f.write('текст')
except TypeError as e:
    print(type(e).__name__)  # → TypeError — 'w' значит 'wb'

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy