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

Alex Martelli aleax at aleax.it
Thu Dec 25 12:02:37 EST 2003


bmgz wrote:

> Hiya,
> 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..

Right -- files are in fact made of bits and bytes, "replacing a line" (with
one which has a different number of bytes) is not an existing basilar
operation on today's filesystems.

Nevertheless, the fileinput module of Python's standard library lets you
simulate "in-place changes", line by line, in textfiles, quite simply.


import fileinput

for line in fileinput.input(['thefile.txt'], inplace=True):
    if fileinput.isfirstline():
        print "the alternative line goes here"
    else:
        print line,        # just pass it through -- note the comma!


Alex





More information about the Python-list mailing list