[portland] List Indexing Confusion

Ryan Roser ryanroser at gmail.com
Fri Aug 12 00:00:27 CEST 2011


I think the problem is with how you're referencing the row from indata.  I'm
not quite sure what you're trying to do with i and j.  I'd get rid of i and
j and replace the for loop with the following:

for row in indata:
    for parm, rowval in zip(parmlist,row[1:]):
        outdata.writerow([loc, row[0], parm, rowval])

(I didn't try the code out, so there may be a typo or some other error.)

Ryan



On Thu, Aug 11, 2011 at 2:31 PM, Rich Shepard <rshepard at appl-ecosys.com>wrote:

>  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
> ______________________________**_________________
> Portland mailing list
> Portland at python.org
> http://mail.python.org/**mailman/listinfo/portland<http://mail.python.org/mailman/listinfo/portland>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/portland/attachments/20110811/bcb28ce9/attachment.html>


More information about the Portland mailing list