fileinput.input - newbie question

M

martijn

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)


import fileinput
thefile = fileinput.input('bla.txt',inplace=1,backup='.bak')
for line in thefile:
if line != "1\n":
print 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

Thanks,
GC-Martijn
 
P

Peter Otten

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 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top