fileinput.input('test.txt') => ERROR: input() already active

John Machin sjmachin at
Mon Nov 20 11:23:38 CET 2006

cyberco wrote:
> Ah, thanks!
> Another related question I have: The following piece edits in place,
> but ads whitelines between all lines of a Windows text file. Why?
> ===========================
> fi = fileinput.input('test.txt', inplace=1)
> for l in fi:

Please don't use lowercase "L" as a variable name; it is too easily
confused with the digit 1 in some fonts. Use meaningful names.
>     print l.replace('a', 'b')
> ===========================
fi = fileinput.input('test.txt', inplace=1)
for line in fi:
    print line.replace('a', 'b')

It's nothing to do with whether the file is a "Windows text file" or
not. The reason is that line already has a "\n" i.e. newline character
at the end. The print statement adds another.
(1) change
    print blahblah
    print blahblah, # comma suppresses the added newline
(2) put
    import sys
up the front and change
    print blahblah


More information about the Python-list mailing list