Abbey Workshop

Python: Reading a File

This little tip covers how to read a text file with Python. What follows are three example Python scripts, that cover different syntax choices and and styles for the same task. I am sure these examples do not include all the possible options but hopefully would work in most situations.

Read File Using readline()

In this example, a infinite loop is created by the while statement on line 6. Line 7 reads the file one line at a time. Line 8 checks to see if the lineStr variable is empty. If it is, the script breaks out the loop and ends. Otherwise, the script increases the line count and prints out the line.

readfile1.py

   1:#!/usr/bin/python
   2:myfile = open('const.txt', 'r')
   3:
   4:# Print out and number each line
   5:count =  0
   6:while 1:
   7:    lineStr = myfile.readline()
   8:    if not(lineStr):
   9:        break
  10:    
  11:    count = count + 1
  12:    print "#:",count,lineStr.rstrip()
  13:    
  14:myfile.close()

Read File Using readlines()

This example is very similar to the first, but instead of using a while loop, a for loop is used. The readlines() method reads all the lines in a file into an array. The for loop then iterates through the array one line at a time.

readfile2.py

   1:#!/usr/bin/python
   2:
   3:# Print out and number each line
   4:count = 1
   5:myfile = open('const.txt', 'r')
   6:
   7:for lineStr in myfile.readlines():
   8:    print "Line",count,lineStr,
   9:    lineStr = myfile.readline()
  10:    count = count + 1
  11:    
  12:myfile.close()

Read a File into a List

The third option is my favorite. It is a minor tweak to the second example. The file is explicitly read into a list. Then, that list is passed to the for loop. If the files are relatively small, there is a preferable option as multiple tasks could be performed on the same file in memory.

Here is a link to a text file that can be used for testing.

readfile3.py

   1:#!/usr/bin/python
   2:
   3:# Print out and number each line
   4:count = 1
   5:myfile = open('const.txt', 'r')
   6:
   7:fileList = myfile.readlines()
   8:
   9:for lineStr in fileList:
  10:    print "Line",count,lineStr,
  11:    lineStr = myfile.readline()
  12:    count = count + 1
  13:    
  14:myfile.close()