change a string in text file then write it

Alex Martelli aleaxit at
Mon Nov 6 21:21:52 CET 2000

"Carel Fellinger" <cfelling at> wrote in message
news:8u6omp$3pu$1 at
> Alex Martelli <aleaxit at> wrote:
> ...
> > for line in fileinput.input("thefile.txt", inplace=1):
> >     if, line):
> >         line = string.replace(line,'foo','bar')
> >     print line
> Ah, this must be one of Alex favorite typos, omitting a trailing ',' :)

<humble attitude='contrite'> yes, I keep doing that (AND omitting
other needed trailing stuff as well -- see a recent post where I
had managed to match 'all strings starting with 0 or more digits'...!-).
<bluff attitude='genial'> Actually, I did it on purpose (what, ME
fall into such a simple trap?!) to see if anybody would notice --
Carel wins the prize, and a special Jury mention for the excellent
explanation that follows...:

> You see, the last line should actually read:
>      print line,    #note the trailing ","
> the lines you get from "fileinput.input('thefile.txt', inplace=1)" have
> a trailing end-of-line symbol embedded if it was there in the input file.
> The print statement adds a trailing end-of-line symbol regardless of
> whether the string to write ended with one, *unless* you end the print
> statement with a comma, then this adding is omitted.


More information about the Python-list mailing list