3.12 File input and output

So far we have taken input from the keyboard and given output to the screen. However, You may want to save the results of a calculation for later use or read in data from a file for Python to manipulate. You give Python access to a file by opening it:

    >>> fout = open("results.dat", "w")

fout is then a variable like the integers, floats and arrays we have been using so far--fout is a conventional name for an output file variable, but you are free to choose something more descriptive. The open function takes two parameters. First a string that is the name of the file to be accessed, and second a mode. The possible modes are as follows:

Mode  Description 
r The file is opened for reading
w The file is opened for writing, and any file with the same name is erased--be careful!
a The file is opened for appending--data written to it is added on at the end

There are various ways of reading data in from a file. For example, the readline() method returns the first line the first time it is called, and then the second line the second time it is called, and so on, until the end of the file is reached when it returns an empty string:

    >>> fin = open("input.dat", "r")
    >>> fin.readline()
    >>> fin.readline()
    >>> fin.readline()

(The \n characters are newline characters.)

Note the parentheses are required. If they are not included the file will not be read. They are to tell Python that you are using the readline() function--a function is always followed by parentheses, whether it takes any arguments or not.

You can see from the example that you tell Python to use methods by adding a full stop followed by the name of the method to the variable name of the file. This syntax may seem strange3.13 but for now just use the examples below as your guide to the syntax, and don't worry about what it means.

The contents are read in as a string but if the data is numeric you need to coerce them into either floats or integers before they are used in calculations:

    >>> fin = open("input.dat", "r")
    >>> x = fin.readline()
    >>> type(x)
    <type 'str'>
    >>> y = float(x)
    >>> type(y)
    <type 'float'>
    >>> print y

You can also use the readlines() method (note the plural) to read in all the lines in a file in one go, returning a list:

    >>> fin.readlines()
    ['This is the first line of the file.\n', 'Second line of the file\n']

To output or write to a file use the write() method. It takes one parameter--the string to be written. If you want to start a new line after writing the data, add a \n character to the end:

    >>> fout = open("output.dat", "w")
    >>> fout.write("This is a test\n")
    >>> fout.write("And here is another line\n")
    >>> fout.close()

Note that in order to commit changes to a file, you must close() files as above.

write() must be given a string to write. Attempts to write integers, floats or arrays will fail:

    >>> fout = open("output.dat", "w")
    >>> fout.write(10)
    Traceback (most recent call last):
      File "<pyshell#65>", line 1, in ?
    TypeError: argument 1 must be string or read-only character
    buffer, not int

You must coerce numbers into strings using the str() function:

    >>> x = 4.1
    >>> print x
    >>> str(x)

If you are trying to produce a table then you may find the $\backslash$t character useful. It inserts a tab character, which will move the cursor forward to the next tabstop3.14. It is an example of a non-printed character. It leaves only white space--no characters are printed as such. However, it is still a string character, and must be enclosed in quotes. For example, to print the variables a and b separated by a tab you would type:

    print a + "\t" + b

This is not a perfect method of producing a table. If you are interested in the ``right way'' of doing this, then ask a demonstrator about formatted output.

Recreate the one hundred element arrays of $\sin$ and $\cos$ you created in Exercise 3.10. Print these arrays out to a file in the form of a table. The first line of the table should contain the first element of both arrays, the second line the second element, an so on. Keep the file as we will use it later.


... strange3.13
It is actually the first you have really seen of Object Orientated Programming, a powerful way of programming and thinking about problems that will not be discussed in this course.
... tabstop3.14
Tabstops are generally separated by eight characters.