1,105,352 Community Members

Writing multiple lines into a file in Python

Member Avatar
kes_ee
Newbie Poster
16 posts since Jun 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
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.

Member Avatar
Ene Uran
Posting Virtuoso
1,822 posts since Aug 2005
Reputation Points: 610 [?]
Q&As Helped to Solve: 278 [?]
Skill Endorsements: 10 [?]
 
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 three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article