Files, Seek, and Readlines. A newbie question

Steven Majewski sdm7g at Virginia.EDU
Mon Apr 1 16:08:47 EST 2002


* seek() always seeks to a byte location in a file.
  There is no seek to a line.

* readlines() reads ALL of the lines in a file. If you do:

 >>> lines = file.readlines()

  then the first line is  'lines[0]' and the 49th line is 'lines[48]'.
  (The optional argument to readlines() is the blocking size -- how
   much to read at a chunk, and is there for optimizing the reads.)
  readline() always reads the next line in the sequence.

* You should try reading the docs at <http://www.python.org/doc/>.
  The docs for file object methods are at:
  <http://www.python.org/doc/current/lib/bltin-file-objects.html>

* If you want to seek to a particular place in a file, you should
  write fixed length records rather than variable length lines of
  text. The reason you can't seek to a line in a file is that there's
  no way of knowing where the next line starts until you have read
  the line before it, so to read the 50th line, you have to read
  lines 1 to 49. If you use fixed length records, the to seek to
  the 50th record, you seek to the  50*size_of_record_in_bytes byte
  in the file.


Is this a homework assignment ? We seem to be getting variations on
this question a lot all of a sudden.


-- Steve Majewski







More information about the Python-list mailing list