Reading and Iterating Over Lines

Once you have a file reference, the object returned by the open function, Python provides three methods to read data from that reference. The read() method returns the entire contents of the file as a single string (or just some characters if you provide a number as an input parameter. The readlines() method returns the entire contents of the file as a list of strings, where each item in the list is one line of the file. The readline() method reads one line from the file and returns it as a string.

Here is a summary of these methods:

Method NameUseExplanation
writefileRef.write(a_string)Add a string to the end of the file. fileRef must refer to a file that has been opened for writing.
read(n)fileRef.read([n])Read and return a string of n characters, or the entire file as a single string if n is not provided. (Note, n is in square brackets, which indicates that n is optional.)
readline()fileRef.readline()Read and return the next line of the file with all text up to and including the newline character.
readlines()fileRef.readlines()Returns a list of strings, each representing a single line of the file.

In this course, we will generally either iterate through the lines returned by readlines() with a for loop, or use read() to get all of the contents as a single string.

Iterating over lines

 Because readlines() returns a list of lines of text, we can use the for loop to iterate through each line of the file.

line of a file is defined to be a sequence of characters up to and including a special character called the newline character. If you evaluate a string that contains a newline character you will see the character represented as \n. If you print a string that contains a newline you will not see the \n, you will just see its effects (a carriage return).

As the for loop iterates through each line of the file, the loop variable will contain the current line of the file as a string of characters. The general pattern for processing each line of a text file is as follows:

file_contents_list = myFile.readlines()
for line in file_contents_list:
    statement1
    statement2
    ...

To process all of our Olympics.txt data found in the following example, we will use a for loop to iterate over the lines of the file. Using the split() function, we can break each line into a list containing all the fields of interest about the athlete. We can then take the values corresponding to name, team, and event to construct a simple sentence.

Reading File Examples

Reading A File

Programming Exercise

In the following exercise you will find a .txt file that contains a poem. You will count and print how many characters, words and lines the file has. Using the split(” “) function will help in trying to determine the amount of words. The above examples should help with the other two statistics. (Note the ” ” in the previous reference to the split() function; that is the delimiter to be used.)

File Statistics