[Tutor] how to write a line

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Jul 25 23:18:08 CEST 2005

On Mon, 25 Jul 2005, nephish wrote:

> i know how to read the lines of a txt file.
> i know how to write a txt file.
> but how do i overwrite a line value with another value ?
> i mean, how do go to, say, line 3 of a text file and replace what is
> written on line 3 with something else?

Hi Nephish,

It's slightly difficult to replace a single line of a file if all of the
lines are different lengths.

But if you can hold the whole file in memory at once, then the following
should work:

    readlines() the file's contents into a list.

    Do changes on that list of lines.

    writelines() all the lines back out.

So the idea is that we use an intermediate list and do all our work on
that list first.  We treat the files just as storage.

Does this make sense?  Please feel free to ask more questions about this.

More information about the Tutor mailing list