opening and reading a file
Consider the following example to open and read file contents
filename = raw_input('Enter file name: ') file = open(filename, 'r') allLines = file.readlines() file.close() for eachLine in allLines: print eachLine
We originally described how this program differs from most standard file access in that all the lines are read ahead of time before any display to the screen occurs. Obviously, this is not advantageous if the file is large. In those cases, it may be a good idea to go back to the tried-and-true way of reading and displaying one line at a time:
filename = raw_input('Enter file name: ') file = open(filename, 'r') done = 0 while not done: aLine = file.readline() if aLine != " ": print aLine, else: done = 1 file.close()
In this example, we do not know when we will reach the end of the file, so we create a Boolean flag done, which is initially set for false. When we reach the end of the file, we will reset this value to true so that the while loop will exit. We change from using readlines()to read all lines to readline(), which reads only a single line. readline() will return a blank line if the end of the file has been reached. Otherwise, the line is displayed to the screen.