[Tutor] Writing to a file...
pythonTutor at venix.com
Tue Sep 14 22:03:21 CEST 2004
On Tue, 2004-09-14 at 15:26, 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
print >> outfile, 'You have ', numofcoins, 'coins totaling $', money
This redirects print statements to a file.
For this kind of filling variables into a string, you can use the string
% operater (string interpolation)
"You have %d coins totaling $%.2f\n" % (numofcoins, money)
builds your output line with a terminating new-line so that it is ready
for write. Omit the \n if it will be printed.
For details see:
It's worth reading because it can do more than this simple illustration.
> >>>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?
> -Greg Bartz
> Tutor maillist - Tutor at python.org
More information about the Tutor