Abbey Workshop | ||||||||||
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.
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.
Download source for: readfile1.py
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.
Download source for: readfile2.py
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.
Download source for: readfile3.py
Copyright © Abbey Workshop 2006