Get number of lines in file

S

ssmith579

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.
 
E

Elliot Temple

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())

-- Elliot Temple
http://www.curi.us/
 
S

Steven Bethard

Elliot said:
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
 
M

Magnus Lycka

Thanks! I was trying len(cpn_version) and that didn't work.

What's your problem? You get a value that's one more than
you expected? You should use splitlines() instead of split('\n'),
or easier, use readlines() instead of read(). Of course, with
a modern python you can just iterate over the file, but note
the difference between split and splitlines when the last line
is complete and ends with a newline character:
.... sdfgsdfgsdfg
.... sdfgsdfgsdfg
.... sdfgsdfgsdfg
.... """
>>> a 'dgdgsdfg\nsdfgsdfgsdfg\nsdfgsdfgsdfg\nsdfgsdfgsdfg\n'
>>> a.split('\n') ['dgdgsdfg', 'sdfgsdfgsdfg', 'sdfgsdfgsdfg', 'sdfgsdfgsdfg', '']
>>> a.splitlines() ['dgdgsdfg', 'sdfgsdfgsdfg', 'sdfgsdfgsdfg', 'sdfgsdfgsdfg']
>>>

If you're allergic to splitlines ;) you could do...
['dgdgsdfg', 'sdfgsdfgsdfg', 'sdfgsdfgsdfg', 'sdfgsdfgsdfg']

....but it depends how you want to view files that end with
several linefeeds in a row (or other whitespace for that
matter).
.... dfgdfg
....
.... dgfdfg
....
....
....
.... """
>>> a.split('\n') ['"dfgdfg', 'dfgdfg', '', 'dgfdfg', '', '', '', '']
>>> a.splitlines() ['"dfgdfg', 'dfgdfg', '', 'dgfdfg', '', '', '']
>>> a.rstrip().split('\n')
['"dfgdfg', 'dfgdfg', '', 'dgfdfg']

In other words, the right solution depends on what behaviour
you want for such cases (if they might exist with your files).

Experimenting like this with the interpreter is a very
convenient way to get a grip on things in Python, and one of
the reasons that Python debugging is usually quicker than
debugging in other languages.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top