[Tutor] Suggestions to improve this first effort?

Kent Johnson kent37 at tds.net
Sun Feb 17 21:05:25 CET 2008


bob gailer wrote:
> f2 = open(outfile, 'w')
> for line in f1:
> 	if s.startswith(".block"): # start of block
> 		s2 = []
> 	elif s==".endblock":
> 		f2.write(",".join(s2) + "\n")
> 	else: # data record
> 		s2.append('"%s"' % line.strip())


This is nice & concise. I'm surprised though that no one has mentioned 
the csv module yet. Rather than inserting the quotes and commas 
yourself, let the module do it, e.g.

import csv
f2 = open(outfile, 'wb') # Note: open in binary mode for CSV
writer = csv.writer(f2)
for line in f1:
	s = line.strip()
	if s.startswith(".block"): # start of block
		s2 = []
	elif s==".endblock":
		writer.writerow(s2)
	else: # data record
		s2.append(s)

And FWIW I would probably have written it like this, which is a bit 
wordier, more explicit and less flexible than the above, which may be 
good or not depending on your data and expectations:

import csv
...
f2 = open(outfile, 'wb') # Note: open in binary mode for CSV
writer = csv.writer(f2)
itr = iter(f1)
try:
   while True:
     s = itr.next().strip()
     if not s:
       continue
     assert s=='.block'
     name = itr.next().strip()
     addr = itr.next().strip()
     city_st = itr.next().strip()
     zip = itr.next().strip()
     writer.writerow([name, addr, city_st, zip])
     itr.next()
     itr.next()
except StopIteration:
   pass

f2.close()

Kent


More information about the Tutor mailing list