[Tutor] Flat file to associative array...

Sean 'Shaleh' Perry shalehperry@comcast.net
Mon Jul 21 20:49:02 2003


On Monday 21 July 2003 00:44, Alex from Caustic Creations wrote:
> Hello,
>
> What would be the best way to convert a flat file of products into
> a multi-dimensional array? The flat file looks like this:
>
> Beer|Molson|Dry|4.50
> Beer|Molson|Export|4.50
> Shot|Scotch|Macallan18|18.50
> Shot|Regular|Jameson|3.00
>

#!/usr/bin/python2.3

import csv

class PipeDialect(csv.Dialect):
    delimiter = '|'
    quotechar = '"'
    escapechar = None
    doublequote = True
    skipinitialspace = False
    lineterminator = '\n'
    quoting = csv.QUOTE_MINIMAL

csv.register_dialect('pipe-based', PipeDialect)

fp = open('/tmp/test.csv')
reader = csv.reader(fp, 'pipe-based')

for row in reader:
    print row

why right parsers when you don't have to (-:
As for the real question you asked, just play arond a little more, you'll get 
it.