开发者

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

开发者 https://www.devze.com 2023-04-08 21:12 出处:网络
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.

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:

"Balan开发者_StackOverflowce 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?


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

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


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号