There are two common ways to read a file: at once and line-by-line. If you need to read more than one file, you should consider putting the code into a function.
Python does not allow for function prototyping so all functions are read into memory before they are used. This is an important dynamic because it means that Python keeps the function in memory until it "sees" that it will not be called again. If you simply copy the same code multiple times, your program is likely to run slower and consume more resources than if you created a function and called it.
You may recall how to analyze a file all-at-once with a Python dictionary. Here is a function to do the same thing:
Using this function, you can probably do the same for reading a file line-by-line. If you do not understand what this function does, you may want to read "How to Analyze a File All-At-Once Using a Dictionary".
Python does not allow for function prototyping so all functions are read into memory before they are used. This is an important dynamic because it means that Python keeps the function in memory until it "sees" that it will not be called again. If you simply copy the same code multiple times, your program is likely to run slower and consume more resources than if you created a function and called it.
You may recall how to analyze a file all-at-once with a Python dictionary. Here is a function to do the same thing:
def readFile(fileHandle, dictName):
line = fileHandle.readline()
dictName = {}
keycounter = 1
while line:
key = str(keycounter)
dictName[key] = line
keycounter = keycounter + 1
line = fileHandle.readline()
return dictName
Simply call the function with the name of the file handler and the name of the dictionary into which you want the file read. The above code assumes that you have already initialised a dictionary in the appropriate name.
Using this function, you can probably do the same for reading a file line-by-line. If you do not understand what this function does, you may want to read "How to Analyze a File All-At-Once Using a Dictionary".

Why not just use a list and file(…).readlines() instead? Why waste time by writing ten lines of code when you can get the same using two calls (constructor / method)?
Felix,
Thanks for your suggestion. It is certainly more efficient than the dictionary method and is worth highlighting. I have drawn attention to it in today’s blog post.