[Tutor] code improvement for beginner ?

Kent Johnson kent37 at tds.net
Sat Oct 22 01:39:28 CEST 2005

Jacob S. wrote:
>> Text mode is the default, you have to specify the 'b' if you want 
>> binary mode. And open() seems to accept any mode quite happily:
>> >>> f=open('build.xml', 'rt')
>> >>> f
>> <open file 'build.xml', mode 'rt' at 0x0096C9B0>
>> >>> f.close()
>> >>> f=open('build.xml', 'rabcd')
>> >>> f
>> <open file 'build.xml', mode 'rabcd' at 0x0096C9F8>
>> Kent
> I'll bet you'll find that open() is coded something like the following
> def open(filename,mode="r"):
>    if mode = 'w':
>        dosomething()
>    if mode = 'wb':
>        dosomething()
>    if mode = 'w+':
>        dosomething()
>    if mode = 'rb':
>        dosomething()
>    ...
>    else:
>        dosomething()  # Where this assumes you are using default mode "r"

One of the cool features of Python is that you can look at the source code to answer questions like this.

open() is implemented in Objects/fileobject.c. Not too surprisingly, it delegates to the underlying C implementation for the actual open call. On Windows it converts the name and mode to Unicode and calls _wfopen(); on other platforms it calls fopen().

The ANSI C standard says,
The argument mode points to a string. If the string is one of the following, the file is
open in the indicated mode. Otherwise, the behavior is undefined.

If the string begins with one of the [below] sequences, the implementation might choose to ignore the remaining characters, or it might use them to select different kinds of a file (some of which might not conform to the properties in 7.19.2).

r open text file for reading
w truncate to zero length or create text file for writing
a append; open or create text file for writing at end-of-file

so it seems the implementation is free to ignore characters it doesn't understand after a valid initial sequence.


More information about the Tutor mailing list