4.5.5 Reading and writing files

As usual, reading and writing files was slightly problematic. The possible reason for difficulty reading is discussed above (see Section 4.4: the consideration of formatted input). Writing was also problematic but for a different reason. Up until they were asked to write to file students had been using the extremely powerful print statement, which takes a lot of the hard work out of printing results to screen. However the write method of a file object which is used to write to file cannot take several arguments; it may only take one argument and that must be of type string.

For example one may use print "Hello", name to greet a person by printing to screen but separating multiple arguments with commas makes the write file object method raise an error:

    >>> f.write("Hello", name)
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    TypeError: function takes exactly 1 argument (2 given)

This is confusing to students who had previously been separating many, arbitrarily-typed variables with commas and using the print statement to print them to screen.

The workaround used during the trial was to have students join strings using the + operator (note the addition of a space--the + operator does not insert one):

    f.write("Hello " + name)

Many students did not coerce numbers into strings before attempting to concatenate:

    >>> x = 5.1
    >>> f.write("x is " + x)
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    TypeError: cannot concatenate 'str' and 'float' objects

A better solution would have been to avoid the overloading of + and use the ability of print to write to files in much the same way as the Unix command line allows for redirection of the standard output stream which was introduced in Python 2.0:

    print >> fout, "x is", x

Unfortunately I was not aware of this feature until after the trial, when it was pointed out to me by Guido van Rossum.

Using this method of writing to file partially addresses one of the apparent syntactic inconsistencies of Python, namely it's OOP-derived method syntax. All objects have ``methods'' which are ways of operating on the objects. For example, if l is a list, one can append another value to it using the append method

    >>> l = [1,2]
    >>> l.append(3)
    >>> print l
    [1, 2, 3]

Note the lack of an assignment statement; it is not written l = l.append(3). This is different to the equivalent procedural construct which would generally involve an assignment of a result. This syntax is one of the few things in the handbook which is ``hand-waved'' away. In the course it is only used for file methods: fin.readline(), fout.write(), etc. If one of the objects of the course is to ``hand-wave'' as few things as possible away, the print » fout, ... construct removes the need for the fout.write method (although not fin.readline().