fileinput.input('test.txt') => ERROR: input() already active
John Machin
sjmachin at lexicon.net
Mon Nov 20 05:23:38 EST 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.
Either:
(1) change
print blahblah
to
print blahblah, # comma suppresses the added newline
or
(2) put
import sys
up the front and change
print blahblah
to
sys.stdout.write(blahblah)
HTH,
John
More information about the Python-list
mailing list