Simon Needham
Simon Needham

Reputation: 543

How to use Python's DictReader class in the csv library?

I'm getting to grips with my first Python project and have got pretty stumped trying to use Python's csv.DictReader class to consume a CSV file.

Code is as follows:

import os
import csv

f = open('MyCsvFile.txt', 'rb')
d =  csv.Sniffer().sniff(f.read(1024), ',')
csvDict = csv.DictReader(csvfile = f, dialect = d)

for line in csvDict:
    print line['Balance Date ']

The csv file roughly looks like this:

"Balance Date ","Currency Code ","Main Account","Balance Float  - 1 Day",... forty more fields
"09/01/2011","EUR","4000519","                .00",...
"09/01/2011","GBP","4000519","                .00",...
"09/01/2011","JPY","4000519","                .00",...

Python is not liking my use of DictReader

g:\work\csvtest>python csvtest.py
Traceback (most recent call last):
  File "csvtest.py", line 6, in <module>
    csvDict = csv.DictReader(csvfile = f, dialect = d)
TypeError: __init__() takes at least 2 arguments (2 given)

Could someone point me in the right direction?

Upvotes: 2

Views: 6775

Answers (2)

S.Lott
S.Lott

Reputation: 392010

According to the code supplied in the documentation, this would work better:

with open('MyCsvFile.txt', 'rb') as source:
    dialect = csv.Sniffer().sniff(source.read(1024), ',')
    source.seek(0)
    csvDict = csv.DictReader(source, dialect)

Upvotes: 2

agf
agf

Reputation: 176950

You need to pass the csvfile as a positional argument, not as a keyword argument:

csvDict = csv.DictReader(f, dialect = d)

Upvotes: 3

Related Questions