[Tutor] Number of lines in a file

Remco Gerlich scarblac@pino.selwerd.nl
Wed, 9 May 2001 12:52:32 +0200


On  0, Praveen Pathiyil <ppathiyi@cisco.com> wrote:
>     How do i find the number of lines in a file (On UNIX)?

You need to read the whole file and count the number of \n in it. 
A file is just a stream of bytes, UNIX doesn't know what a line is.

wholefile = f.read()
lines = wholefile.count("\n")
if wholefile[-1] != "\n":
    lines = lines+1     # If the file doesn't end with \n, add one

Or, equivalently,
lines = len(f.readlines())

If you don't want to have the whole file in memory at the same time,
use fileinput, readlines with a sizehint, or get Python 2.1 and use
lines = len(f.xreadlines())

>     tell() returns the position in terms of characters, right ?

Yes, your current position.

-- 
Remco Gerlich