Newbie question: Replace line in file?

Alex Martelli aleaxit at yahoo.com
Tue Oct 24 11:27:59 EDT 2000


"Carel Fellinger" <cfelling at iae.nl> wrote in message
news:8t454v$p9p$1 at animus.fel.iae.nl...
> Alex Martelli <aleaxit at yahoo.com> wrote:
> ...
> > for line in fileinput.input(onefilename, inplace=1):
> >     print line.replace(old,new)
>
> there should be a trailing ',' at the end of that print statement, like:
>
>       print line.replace(old,new),

Good point, and, to expand: fileinput.input, like other
ways to read a file one line at a time, does NOT remove
the trailing newline char from the returned string. This
is quite important, since it guarantees that when an
EMPTY string is returned it means end-of-file -- there
is no ambiguity with an empty-line, since the latter will
have the end-of-line character; this is not crucial here,
since the for-loop is in control anyway, but it does
become crucial if you're using alternate constructs to
control the reading-loop, such as a while-loop.

So, since "line" already has a newline, we do NOT want
the print to add another one -- whence the need for the
trailing-comma (which tells print to omit its normal,
default newline-at-end).

Alternatively,
    sys.stdout.write(line.replace(old,new))
will also work, but print-with-comma-at-end is more
concise and (arguably) readable.


Alex






More information about the Python-list mailing list