fileinput.input - newbie question

Peter Otten __peter__ at web.de
Fri Sep 2 06:11:36 EDT 2005


martijn at gamecreators.nl wrote:

> I'm testing some writing/reading with a file and i'm not sure if it is
> possible to print/use the line with fileinput.input inplace=1 (see
> below)

fileinput.input(inplace=True) redirects stdout to the file[s] given as its
first parameter. Instead of appearing on the screen the output of print
statements is therefore written to the file currently being read (there are
actually two files, just like in your alternative approach).

You can work around redirection by saving a copy of the original stdout:

> import fileinput
  import sys
  original_stdout = sys.stdout
> thefile = fileinput.input('bla.txt',inplace=1,backup='.bak')
> for line in thefile:
>     if line != "1\n":
          # this is written to 'bla.txt'
>         print line,
          # this is written to the screen (if you don't 
          # redirect stdout externally)
          print >> original_stdout, line,
> 
>     #is it possible to 'use' / print the 'line' on the screen here?
> 
> thefile.close()

> When its not possible then I use 2 file's filein.txt,fileout.txt

I would prefer that for its conceptual simplicity.

Peter




More information about the Python-list mailing list