Python Glossary Русский

all Python 3codecsterm

codecs.StreamRecoder

stream codecs

A transcoding wrapper over a binary stream: bytes in one encoding outside, in another inside. It is usually created with codecs.EncodedFile.

Syntax

codecs.StreamRecoder(stream, encode, decode, Reader, Writer, errors='strict')

Its constructor takes six parameters in an easily confused order: encode and decode are functions for the OUTER side, Reader and Writer are classes for the file's encoding. That is why people almost always go through EncodedFile. Both reads and writes use bytes, not str: it never hands text out.

Examples

import codecs, io
raw = io.BytesIO('ёж'.encode('cp1251'))
rec = codecs.StreamRecoder(raw, codecs.getencoder('utf-8'), codecs.getdecoder('utf-8'),
                           codecs.getreader('cp1251'), codecs.getwriter('cp1251'))
print(rec.read())  # → b'\xd1\x91\xd0\xb6'
print(type(codecs.EncodedFile(io.BytesIO(), 'utf-8')).__name__)  # → StreamRecoder

See also

Open in the full glossarydocs.python.orgReport an inaccuracy