Python Glossary Русский

all Python 3fileinputfunction

fileinput.hook_compressed()

opening hooks

An opening hook for fileinput: transparently decompresses .gz and .bz2 files and opens the rest with plain open().

Syntax

fileinput.hook_compressed(filename, mode, *, encoding=None, errors=None)

Compression is detected only by the extension, not by the content: an archive without .gz is read as garbage. Text from an archive is decoded with the locale encoding unless you pass encoding='utf-8' to input() — cp1251 on a Russian Windows. The hook does not know .xz; inplace=True cannot be combined with openhook.

Examples

import fileinput, gzip
with gzip.open('log.txt.gz', 'wt', encoding='utf-8') as g:
    g.write('строка 1\nстрока 2\n')
open('plain.txt', 'w', encoding='utf-8').write('строка 3\n')
with fileinput.input(['log.txt.gz', 'plain.txt'], openhook=fileinput.hook_compressed, encoding='utf-8') as f:
    print(len(list(f)))  # → 3

See also

Open in the full glossarydocs.python.orgReport an inaccuracy