python 2.3, cvs module specific question

Peter Otten __peter__ at web.de
Wed Sep 3 17:57:31 EDT 2003


Bernard Delmée wrote:

> Hello, I can't seem to be able to specify the delimiter when building a
> DictReader()
> 

DictReader currently does not accept parameters for creating a dialect on
the fly. See Bug #792558.

> One rather convoluted workaround is the following:
> 
>      inf = file('data.csv')
>      d = csv.Sniffer().sniff(s)
>      inf.seek(0)
>      headers = inf.readline().split(';')
>      rd = csv.DictReader( inf, headers, dialect=d )
>      for row in rd:
>          # ...
> 

Another workaround might be (untested)

class MyDialect(csv.excel):
    delimiter = ";"
   
inf = file('data.csv')
headers = inf.readline().split(';')
rd = csv.DictReader(inf, headers, dialect=MyDialect)

Of course your version should be more general, especially if you replace the
literal ';':

headers = inf.readline().split(d.delimiter)


Peter





More information about the Python-list mailing list