Name
EncodedFile
Synopsis
EncodedFile(file
,datacodec
,filecodec
=None,errors
=’strict')
Wraps the file-like object file
, returning
another file-like object ef
that
implicitly and transparently applies the given encodings to all data
read from or written to the file. When you write a string
s
to ef
,
ef
first decodes
s
with the codec named by
datacodec
, then encodes the result with
the codec named by filecodec
, and lastly
writes it to file
. When you read a string,
ef
applies
filecodec
first, then
datacodec
. When
filecodec
is None
,
ef
uses
datacodec
for both steps in either
direction.
For example, if you want to write strings that are encoded in
latin-1
to sys.stdout
and have
the strings come out in utf-8
, use the following:
import sys, codecs sys.stdout = codecs.EncodedFile(sys.stdout,'latin-1', 'utf-8')
Get Python in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.