Get number of lines in file

Steven Bethard steven.bethard at gmail.com
Fri May 27 22:24:49 EDT 2005


Elliot Temple wrote:
> 
> On May 27, 2005, at 12:17 PM, ssmith579 at aol.com wrote:
> 
>> I have read in a file and need to get the number of lines.
>>
>>     cpn_file = open('Central Part number list.txt')
>>     cpn_version = cpn_file.read().split('\n')
>>
>> I want to know the number of elements in cpn_version.
> 
> Could you use:
> 
> count_lines = len(cpn_file.readlines())

Or if you're worried about reading all of cpn_file into memory at once, 
you could try something like:

     sum(1 for line in cpn_file)

or in Python 2.3:

     sum([1 for line in cpn_file])

STeVe



More information about the Python-list mailing list