Best practice way to open files in Python 2.6+?

Antoine Pitrou solipsis at pitrou.net
Tue Jul 27 10:57:42 EDT 2010


On Tue, 27 Jul 2010 10:33:06 -0400
python at bdurham.com wrote:
> What is the best practice way to open files in Python 2.6+
> 
> It looks like there are at least 3 different ways to open files:
> - built-in open()
> - io.open()
> - codecs.open()
> It seems like io.open() combines the best of the built-in open()
> and the codecs open(). Am I missing any obvious drawbacks to
> using io.open() except for backwards compatibility?

io.open() is quite slow in 2.6, although the performance issues are
fixed in 2.7 (and in 3.1).

io.open() is much stricter in what types it accepts and emits. Files
opened in text mode, for example, will return unicode strings when
reading and will only accept unicode strings for write().
(similarly, files opened in binary mode will only accept bytestrings
for write())

Regards

Antoine.





More information about the Python-list mailing list