all Python 3codecsfunction
codecs.EncodedFile()
stream codecs
Wraps a binary file in a StreamRecoder for on-the-fly transcoding: bytes in one encoding outside, bytes in another inside the file.
Syntax
codecs.EncodedFile(file, data_encoding, file_encoding=None, errors='strict')
The trap is the direction: both writing and reading use bytes, not strings, so write('text') raises TypeError and you need write('text'.encode('utf-8')). data_encoding is the encoding of the bytes on your side, file_encoding the one in the file. Closing the wrapper closes the underlying file. The everyday job 'read cp1251, save as UTF-8' is simpler with two open calls and encoding.
Examples
import codecs, io
raw = io.BytesIO('ёж'.encode('cp1251'))
f = codecs.EncodedFile(raw, data_encoding='utf-8', file_encoding='cp1251')
print(f.read()) # → b'\xd1\x91\xd0\xb6' — уже UTF-8
try:
f.write('ёж')
except TypeError:
print('нужны bytes') # → нужны bytes
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy