how to write a line in a text file

Steve Holden steve at holdenweb.com
Mon Jul 25 15:51:42 EDT 2005


nephish at xit.net wrote:
> Hey there,
> kinda newbie question here.
> 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?
> 
> thanks
> <><
> 
You shouldn't try do "update in place" like that unless your file has 
fixed-length lines or records. Altering the length of an existing file 
isn't to be lightly undertaken, and even when possible will likely not 
be undertaken.

The classic way to approach this problem is to read the file as input, 
processing its contents and writing a new file, which eventually 
replaces the original in a fairly complex dance of renaming and deletion.

In Python you can use a text file's readlines() method to build a list 
of all the lines in a file. That makes it quite easy to change numbered 
lines. Having modified the file's content in memory you can then create 
a new file using the writelines() method of a new file. The trick is to 
avoid losing both the old and the new files when a low-probability crash 
occurs.

Since you are newbile (?) I would advise against paranoia - write your 
code without worrying about error handling. You'll be pleased to know 
that when you start to take a serious interest in error handling Python 
has everything you'll need.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC             http://www.holdenweb.com/




More information about the Python-list mailing list