Best practice for opening files for newbies?

Chris Angelico rosuav at gmail.com
Thu Sep 18 18:37:42 CEST 2014


On Fri, Sep 19, 2014 at 2:19 AM,  <chris.barker at noaa.gov> wrote:
> So: there are way too many ways to open a simple file to read or write a bit of text (or binary):
>
> open()

Personally, I'd just use this, all the way through - and not importing
from io, either. But others may disagree.

Be clear about what's text and what's bytes, everywhere. When you do
make the jump to Py3, you'll have to worry about text files vs binary
files, and if you need to support Windows as well as Unix, you need to
get that right anyway, so just make sure you get the two straight.
Going Py3 will actually make your job quite a bit easier, there; but
even if you don't, save yourself a lot of trouble later on by keeping
the difference very clear. And you can save yourself some more
conversion trouble by tossing this at the top of every .py file you
write:

from __future__ import print_function, division, unicode_literals

But mainly, just go with the simple open() call and do the job the
easiest way you can. And go Py3 as soon as you can, because ...

> because that is still what most of the code "in the wild" is in.

... this statement isn't really an obvious truth any more (it's hard
to say what "most" code is), and it's definitely not going to remain
so for the long-term future. For people learning Python today, unless
they plan on having a really short career in programming, more of
their time will be after 2020 than before it, and Python 3 is the way
to go.

Plus, it's just way WAY easier to get Unicode right in Py3 than in
Py2. Save yourself the hassle!

ChrisA



More information about the Python-list mailing list