[Tutor] file operations and formatting

Magnus Lycka magnus@thinkware.se
Tue Dec 17 06:10:02 2002


At 18:58 2002-12-16 -0500, andy surany wrote:
>I knew that I was close.... I had tried '%4.2f %s' % (file.write (a,b))

Try to do things one step at a time when you don't
understand what you are doing, never several things
at once. First create the string with the look you
like and put it in a local variable. Then you print
it so that you know what you did. When it comes out
looking right on the console as you print it, it might
be time to consider adding code to write it to a file.

I think you realize that you should create the string
before you write it to the file, right? So if you do
one thing per line of code, you will reduce the risk of
inadvertantly doing things in wrong order.

Also, make sure that you get a habit of using meaningful
variable names, otherwise your programs will be confusing.
You don't feel that right now, but others will, and you
will too what you get back to them after a year or so...
Unless you make an effort to always write meaningful names,
you will use names like a and b even when it really matters
(at least if you are human like the rest of us... ;)

Then we could have had something like:

report = open('junk.txt','w')
value = 99.9
unit = 'kg'
measurement = "%.2f %s" % (value, unit)
#print measurement
report.write(measurement)

If you didn't understand how to create a string with
the formatting syntax, you could do

measurement = str(value) + ' ' + unit

for the time being, and fix that later.

So, try never to do more than one thing per line of code
unless you really know what you are doing!


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se