Reading the whole file

Here is a code fragment illustrating how to read a file called input and display its contents on the screen (or standard output).

fp = open("input", "r")
for line in fp:

In the above example, first we open the file and create a file object called fp. The "r" specifies that the file is to be read. It is optional.

Once the file is open we can read all the lines in the file using a for loop, treating the file object fp as if it was just a list of lines. There is a subtlety here. Each line of the file is a string of characters that ends with a new-line character (\n). (That special character is invisible, but on your screen it triggers a new line.) The rstrip() function is used to remove that new-line character. (It also removes any other non-printing spaces and tabs.) If we didn't do that, the output would look double-spaced because the print statement adds its own new-line character to the end of its output.

The rstrip() function is appended to the string line after a dot (period). This sort of function is called a “method”. Every string has this method. To invoke it you simply attach .rstrip() to the variable (or even a string constant).

Notice that we use the close() method of the file object fp to close the file. Why do this? It uses some memory to keep the file open, so this frees up the memory. The operating system may have a limit to the number of open files. Also, once you close it, you can reread it if you want to later on. When your code finishes, the file is closed, anyway.

Some practitioners like to use a different syntax for doing the same thing:

with open("input") as fp:
    for line in fp:

In this case the file is automatically closed.