[Tutor] Writing to a file...
kent_johnson at skillsoft.com
Tue Sep 14 21:48:11 CEST 2004
Use "print chevron" to direct the print to the file:
print >> outfile, 'You have', numofcoins, 'coins totaling $', money
or use the string format operator % to create a single string for write:
outfile.write('You have %d coins totalling $%d\n' % (numofcoins, money))
Note that print appends a newline and write doesn't, so to get equivalent
output you need to explicitly write the newline.
At 02:26 PM 9/14/2004 -0500, Bartz, Gregory H. wrote:
>I'm somewhat new to Python and this is my first question to the list.
>In the example below you can see that it takes four write statements to
>equal one print statement.
>At the moment I'm using print statements and redirecting them to a file
>when I run the script (foo.py > outfile).
>Example using print:
>dimes = 3
>nickels = 5
>numofcoins = dimes + nickels
>money = dimes * 0.1 + nickels * 0.5
>print 'You have ', numofcoins, 'coins totaling $', money
> >>>You have 8 coins totaling $ 0.55
>for the same line, write() is more cumbersome:
>outfile.write('You have ')
>outfile.write(' coins totaling $')
>Is there a more efficient way of doing this, or some way I can redirect
>the output internally?
>Tutor maillist - Tutor at python.org
More information about the Tutor