Carel Fellinger: one more question

Adam DePrince adam at deprince.net
Mon Feb 19 20:57:27 EST 2001


Steve Mak wrote:
> 
> I need to output some data to an output file. I am using:
> 
> outp = open("output.txt","w")
> outp.write(data)
> outp.close()
> 
> my problem is i need to have some data on separate lines. right now
> everything is saved as 1 long line of data. how do I specify a carriage
> return to the output file?

Assuming that data is a sequence, each member representing the contents
of a line
(as opposed to the one-big-blob implied about) you can do this:

outp = open("output.txt","w")
outp.write(string.join(data, "\n"))
outp.close()

If you are using Python 2.0 of better you can say:

outp = open("output.txt","w")
for line in data:
	print >> outp, line
outp.close()

Or, if you lack a version <2.0, but not courage, you can:

outp = open("output.txt", "w" )
old_stdout = sys.stdout
sys.stdout = outp
for line in data:
	print line
sys.stdout = old_stdout
outp.close()

Just make sure your other threads don't disagree with your mistreatment
of stdout ... 


To see where I ripped off my explanation:
http://www.python.org/2.0/new-python.html

Search for "9.1" or "Minor Language Changes."  


Adam DePrince
Starmedia Network, Inc.
Email:
zlib.decompress('x\332KLI\314\325KI-(\312\314KNu(.I,\312MM\311L\324K\316\317\005\000\221\331\012s')



More information about the Python-list mailing list