Get number of lines in file

Magnus Lycka lycka at carmen.se
Mon May 30 06:59:02 EDT 2005


ssmith579 at aol.com wrote:
> 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:

 >>> a = """dgdgsdfg
... 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...

 >>> a.rstrip().split('\n')
['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).

 >>> a = """"dfgdfg
... 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.



More information about the Python-list mailing list