[Tutor] how to write a string into a specific line in a file

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Mar 8 19:46:22 CET 2006

On Wed, 8 Mar 2006, andrew clarke wrote:

> On Tue, Mar 07, 2006 at 11:18:27AM -0000, Alan Gauld wrote:
> > > I was wondering if it is possible to write a string to a specific line
> > > in a file without reading in the whole file in as the below.
> >
> > Some languages, such as COBOL and some BASICs etc support
> > random access files, unfortunately Python doesn't (Although I'll be
> > amazed if somebody hasn't cooked up (or is cooking up) a module
> > that does it)
> You then go on to mention file.seek().  I thought that seek() provided
> "random access", ie. to seek to anywhere at random in a file.  Can you
> clarify what you mean by "random access files"?

Hi Andrew,

I think Alan's referring to be able to go to any arbitrary line in a file
or insert arbitrary lines in a file in those other languages.

The Python core language gives us random access to a file's byte content
by using seek(), but we can't do arbitrary insertion without pushing all
the other bytes to the right.

If it helps, imagine a list that doesn't allow for insert(), but does
allow for appends().

    L = ['a', 'c', 'd']

If we wanted to get a 'b' into there in the right place, we could go about
it this way:

    L.append('b')                ## ['a', 'c', 'd', 'b']
    L[2], L[3] = L[3], L[2]      ## ['a', 'c', 'b', 'd']
    L[1], L[2] = L[2], L[1]      ## ['a', 'b', 'c', 'd']

That is, we bubble the 'b' down.  Or looking at it another way, we push
and shove everything to the right of our insertion point to make room for
the insertion.

This impovershed interface is pretty much what we have with files.  We're
allowed to seek(), read(), and write(), but we're not given insert() as a
primitive operation, because that's not an operation that's easy to do
with files directly.  It's doable, but it's painful and expensive.

That's why programs that have to do things like insertion or deletion on a
text file will load the file's contents into a list, work on the list, and
then spit that list back into the file. It's just easier and faster to use
a list as our intermediary.

I hope this helps!

More information about the Tutor mailing list