[portland] List Indexing Confusion
Rich Shepard
rshepard at appl-ecosys.com
Thu Aug 11 23:31:34 CEST 2011
Once again it's been too long since I've written a script; every time I
mean to finish a model I've been writing a more critical business need has
pushed the coding back.
I'm now faced with translating a couple of dozen spreadsheets (saved as
.csv files) into the proper format for insertion into a database table. My
brain refuses to get the row indexing correct.
Here is the first few rows of a typical file:
CVS
Arsenic:Zinc:Nitrate Nitrogen:pH:Chloride:Sulfate:Total Dissolved Solids
1993-11-22:0.008:0.014:0.021:7.560:2.060:39.3:293.0
I want an output file that looks like
CVS|1993-11-22|Arsenic|0.008
CVS|1993-11-22|Zinc|0.014
etc.
The mal-functioning script is:
-------------------------
#!/usr/bin/env python
import sys,csv
filename = sys.argv[1]
try:
infile = open(filename, 'r')
except:
print "Can't open ", filename,"!"
sys.exit(1)
indata = csv.reader(infile, delimiter=':')
loc = indata.next() # only one field on first line
parmlist = indata.next() # the list of chemicals
outfile = open('out.csv', 'w')
outdata = csv.writer(outfile, delimiter = '|', lineterminator = '\n')
i = 0
j = 0
for row in indata:
outdata.writerow([loc, row[i][j], parmlist[i], row[i][j+1]])
i += 1
j += 1
infile.close()
outfile.close()
--------------------------
List indexing is not that difficult so I am embarrassed to admit that I
don't see what I'm doing incorrectly. A clue would be very helpful.
Rich
More information about the Portland
mailing list