io.open vs. codecs.open

random832 at fastmail.us random832 at fastmail.us
Wed Mar 4 15:00:56 EST 2015


On Wed, Mar 4, 2015, at 07:12, Albert-Jan Roskam wrote:
> Hi,
> 
> Is there a (use case) difference between codecs.open and io.open? What is
> the difference?
> A small difference that I just discovered is that
> codecs.open(somefile).read() returns a bytestring if no encoding is
> specified*), but a unicode string if an encoding is specified. io.open
> always returns a unicode string.

I think this is a historical accident. Originally, in python 2, built-in
open only returned byte strings. Later, codecs was added, and then io
was added after that. Python 3 changed the built-in functions to use the
same classes as io, and now io.open and built-in open are the same. In
new Python 3 code, you should probably always use builtin open. Use
binary mode (mode option has "b" in it) if you want byte strings.



More information about the Python-list mailing list