Opening a file and reading the content of a file is pretty easy in Python. One easy way to read a text file and parse each line is to use the python statement “readlines” on a file object. Python’s “readlines” reads everything in the text file and has them in a list of lines. Here is how to use Python’s “readlines”
## Open the file with read only permit f = open('myTextFile.txt', "r") ## use readlines to read all lines in the file ## The variable "lines" is a list containing all lines lines = f.readlines() ## close the file after reading the lines. f.close()
Then you can go over the list of “lines” to parse each line. As you can immediately notice, “readlines” works great for a small text file. However, it is not memory efficient to use if your text files are really big. A better way to read a text file that is memory-friendly is to read the file line by line, that is one line at a time. Python has (at least) two ways to read a text file line by line easily.
Read a Text File Line by Line Using While Statement in Python
Here is the way to read text file one line at a time using “While” statement. Using the while statement is the best option if you are starting with Python.
## Open the file with read only permit f = open('myTextFile.txt') ## Read the first line line = f.readline() ## If the file is not empty keep reading line one at a time ## till the file is empty while line: print line line = f.readline() f.close()
Read a Text File Line by Line Using an Iterator in Python
One can also use an iterator to read a text file one line at time. Here is how to do it.
f = open('myfile.txt') for line in iter(f): print line f.close()