When parsing files using Python, it's useful to know exactly how many lines are contained in the file. The example in file_lines.py shows a simple method to determine the number of lines contained in a file by first opening it, and then using readlines() to generate a list of lines and using the len() function to determine the number of lines in the list. Note For large files, using readlines() to generate a list lines in a file might be impractical because of the amount of memory and processing time necessary. filePath = "input.txt" lineCount = len(open(filePath, 'rU').readlines()) print "File %s has %d lines." % (filePath, lineCount) file_lines.py File input.txt has 4 lines. Output from file_lines.py code |