[Tutor] Line in a file

alan.gauld@bt.com alan.gauld@bt.com
Fri, 19 Jul 2002 13:44:34 +0100


> How do I go directly to an exact line number in a file?

If the linev length is constant you can use seek() 
to jump directly by passing N*lineLength

Otherwise you have to read N lines:

for i in range(N): line = f.readline()

If the file is not too big it may be faster to read 
the whole lot to a list then index the list:

lines = f.readlines()
line = lines[N-1] # zero indexing

Alan g.