replace line #1 with "newline\n" in text file

Alex Martelli aleax at aleax.it
Thu Dec 25 12:10:09 EST 2003


Erik Max Francis wrote:

> bmgz wrote:
> 
>> I am trying to replace the first line of a config file.. with a new
>> string
>> been googlizing and reading the python manual.. but can't find what I
>> need..
>> it's all rubbish about bits and bytes etc..
> 
> You'll have to read in the file, write out a temporary one, and then
> move the new one over the old one.

Yes, that's basically what fileinput (which I suggested in my other
msg in this thread) does for you behind the scenes.  Of course, such
complication is typically only worth it for potentially big files --
for a small file, one might prefer a "rewrite-in-place" approach, e.g.:

f = file('thefile.txt', 'r+')
lines = f.readlines()
lines[0] = "the new line goes here\n"
f.seek(0)
f.writelines(lines)
f.close()

This should be fine unless the file is huge OR you're unlucky enough
that the machine crashes right while you're rewriting the file...;-)


Alex





More information about the Python-list mailing list