Determining the Number of Lines in a File


lineCount = len(open(filePath, 'rU').readlines()) print "File %s has %d lines." % (filePath, lineCount)

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




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net