1.11M Members

Writing multiple lines into a file in Python

 
0
 

Can this be done in Python?.. which is done in perl.

open(TEST,">test.txt");
*STDOUT = *TEST;
print "print somting...";
print "print somting...";
*STDOUT = *FHSAVE;

All the print statement between the lines "*STDOUT = *FHSAVE;" will be written in to test.txt. Is there any way to do this in python.

Thanks.

 
1
 

In Python it would look like:

fout = open("test1.txt", "w")
fout.write("save something ...\n")
fout.write("save something more ...\n")
fout.close()

# or C++ style (allowed in Python2)
fout = open("test2.txt", "w")
print >>fout, "save something ..."
print >>fout, "save something more ..."
fout.close()

# more like PERL
import sys

old = sys.stdout
sys.stdout = file("test3.txt", "w")
print "save something ..."
print "save something more ..."

# reset
sys.stdout = old
You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article