I am searching for a way to jump to a specific line in a text file, let's
say to line no. 9000.
Is there any method like file.seek() which leads me to a given line instead
of a given byte?
Hope for help
Patrick
If by "jump" you mean without reading the preceding 8999 lines, and by
"text file" you mean variable length records without a separate index
structure, that method hasn't been implemented yet. AFAIK it hasn't
been implemented in any other language either :-)
The linecache module may be what you want, depending on how closely
your access patterns match those the module was designed for.
Cheers,
John
> I am searching for a way to jump to a specific line in a text file,
> let's say to line no. 9000. Is there any method like file.seek()
> which leads me to a given line instead of a given byte?
You can simulate it fairly easily, but it will internally read the
file line by line and will take the time roughly proportional to the
size of the file.
from itertools import islice
def seek_to_line(f, n):
for ignored_line in islice(f, n - 1):
pass # skip n-1 lines
f = open('foo')
seek_to_line(f, 9000) # seek to line 9000
# print lines 9000 and later
for line in f:
print line
The OP gave no impression that he'd restrict himself to one
seek_to_line call per open. Perhaps you need
f.seek(0)
here otherwise
seek_to_line(f, 20)
seek_to_line(f, 10)
will give something unexpected (like jumping forwards instead of
backwards).
Others have given the general answer (No), but if you are lucky enough to have
FIXED length lines you can jump by just calculating the byte offset of the
beginning character in line 9000 by using file.seek() and then read the bytes.
You didn't say anything about the format of the file.
-Larry
As others have said, no. But if you're wondering how other file
formats do this, like BDB or PostgreSQL data files, which absolutely
have to jump to the magical spot in the file where the data is, they
keep an index at the beginning of the file that points to what byte
the data they are looking for is in.
So if it's really important to be able to do this, consider that.