我正在处理我的第一个Python项目,并且试图使用Python的csv.DictReader类来使用CSV文件。
代码如下:
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 ']
csv文件大致如下所示:
"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不喜欢我使用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)
有人能指出我正确的方向吗?
答案 0 :(得分:3)
您需要将csvfile
作为位置参数传递,而不是作为关键字参数传递:
csvDict = csv.DictReader(f, dialect = d)
答案 1 :(得分:2)
根据code supplied in the documentation,这会更好:
with open('MyCsvFile.txt', 'rb') as source:
dialect = csv.Sniffer().sniff(source.read(1024), ',')
source.seek(0)
csvDict = csv.DictReader(source, dialect)