seek in a file

Steven Majewski sdm7g at virginia.edu
Tue Mar 26 18:30:17 EST 2002


On Wed, 27 Mar 2002, Andreas Penzel wrote:

> How to jump to a specified line in a file which is read-opened?
> With seek() I can jump to an exact position of  the complete file in
> "byte-steps".
> Is seek able to jump to a line-number?

	No

 Lines are variable length and delimited by a newline char ( or a pair
of chars on Windows ). There's no way to find the start of the next
line without reading the previous ones. Even systems, like VMS, that
use a different method ( char count followed by chars ) still need
to read each line, because they are still variable length records.
 In other words: this isn't just a language limitation of C or Python
or a limitation of unix I/O libs. Fortran, for example, supports both
direct (random access or 'seekable') access files and sequential access
files, but direct access files must be fixed record length.


> If not, what else can I do?

file.readlines() returns a list of all of the lines in the file:

	lines = open( 'filename' ).readlines()

The first line is in lines[0], the Nth line in lines[N-1].


Are the files too big to fit in memory ?
What do you want to do with the lines ?
( I hope you weren't planning on trying to modify a line in a file:
  because of the variable length on lines, if you don't write
  exactly the same number of chars back, you will either overwite
  the next line, or leave an extra partial line after your edited
  line. Most text editors read the whole file into memory and then
  write out a new file after it's modified in memory. )


-- Steve Majewski







More information about the Python-list mailing list