Python Glossary Русский

all Python 3codecsfunction

codecs.getreader()

stream codecs

Returns the StreamReader class for an encoding; call it with a binary stream to get an object that reads str.

Syntax

reader = codecs.getreader(encoding)(stream)

A common slip is passing the stream to getreader itself: getreader('utf-8')(f) has two pairs of parentheses, and the first returns a class. The stream must be binary: a text file from open(..., 'r') yields str and decoding fails. For files and sockets (sock.makefile) io.TextIOWrapper is usually better.

Examples

import codecs, io
raw = io.BytesIO('строка 1\nстрока 2\n'.encode('cp1251'))
Reader = codecs.getreader('cp1251')
r = Reader(raw)
print(r.readline().strip())  # → строка 1
print(r.readlines())  # → ['строка 2\n']

See also

Open in the full glossarydocs.python.orgReport an inaccuracy