Best practice for opening files for newbies?

chris.barker at noaa.gov chris.barker at noaa.gov
Thu Sep 18 18:19:37 CEST 2014


Folks,

I'm in the position of teaching Python to beginners (beginners to Python, anyway).

I'm teaching Python2 -- because that is still what most of the code "in the wild" is in. I do think I"ll transition to Python 3 fairly soon, as it's not too hard for folks to back-port their knowledge, but for now, it's Py2 -- and I'm hoping not to have that debate on this thread. 

But I do want to keep the 2->3 transition in mind, so where it's not too hard, want to teach approaches that will transition well to py3.

So: there are way too many ways to open a simple file to read or write a bit of text (or binary):

open()
file()
io.open()
codecs.open()

others???

I'm thinking that way to go now with modern Py2 is:

from io import open

then use open() .....

IIUC, this will give the user an open() that behaves the same way as py3's open() (identical?).

The only issue (so far) I've run into is this:

In [51]: f = io.open("test_file.txt", 'w')

In [52]: f.write("some string")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-52-f874778a72a1> in <module>()
----> 1 f.write("some string")

TypeError: must be unicode, not str

I'm OK with that -- I think it's better for folks learning py2 now to get used to Unicode up front anyway.

But any other issues? Is this a good way to go?

By the way: I note that the default encoding for io.open on my system (OS-X) is utf-8, despite:
In [54]: sys.getdefaultencoding()
Out[54]: 'ascii'

How is that determined?

-CHB




More information about the Python-list mailing list