[Tutor] Saving file changes to output
Daniel Yoo
dyoo@hkn.EECS.Berkeley.EDU
Wed, 2 Aug 2000 11:14:59 -0700 (PDT)
On Wed, 2 Aug 2000, Daniel D. Laskey, CPA wrote:
> I've been struggling for the last couple of days on this problem.
> So it is not as if I am asking the group to do my homework for
> me. Again, I'm a newbie. I've been studing hard. Maybe I'm just
> learning impaired. Please be kind.
Don't apologize; we're not high priests or another authority figure!
Don't worry about it --- we're just learning here.
Remco Gerlich has already answered your question on that write() call. I
just wanted to look at a part of your program, to see if we can shorten it
a little:
x = string.split(line,',')
# read each line of file and split at each ","
f1 = x[4]
# pull out the fifth position 0,1,2,3,4 of each line
f2 = '"' + f1 + '"'
# put double quotes " " around this data
f3 = x[0]+","+x[1]+","+x[2]+","+x[3]+","+f2+","+x[5]
# print f3
# rebuild the file using the new position [4] with double quotes
out_file.write(line,f3)
There's a slightly shorter way of writing this. Since you're quoting the
5th element (x[4]), you can say:
x = string.split(line,',')
x[4] = '"' + x[4] + '"' # put double quotes around x[4]
f3 = x[0]+","+x[1]+","+x[2]+","+x[3]+","+x[4]+","+x[5]
Of course, this can be improved on, but it's already a little better.
The reason this is nicer is because we can take advantage of the
regularity in the last statement --- we're just rejoining all the elements
in that list back together. Appropriately, we can use the string.join()
command, which works very closely with splitting. The newest revision
looks like this:
x = string.split(line,',')
x[4] = '"' + x[4] + '"' # quote x[4]
f3 = string.join(x, ",")
which is a little easier to read. Commenting is often a virtue, but I
think you went a little wild on that part. *grin* Hope this helps!