为什么DictWriter不能在我的代码中工作?

时间:2012-08-10 05:26:14

标签: python csv

使用来自互联网的一些帮助,我构建了一个通用函数,它从csv文件中提取特定列并将其读取到由输入指定的字典中。

import csv
def dict_filter(it, keys):
    for d in it:
        yield dict((k, d[k]) for k in keys)

然后我稍后调用此方法,使用DictReaderDictWriter将这些列写入另一个CSV文件:

fieldnames = ["_STATE", "HEIGHT", "WEIGHT", "_BMI", "AGE", "CTYCODE", "IYEAR"]
source = open("data88.csv", 'r')
reader = csv.DictReader(source) 
result = open("aggregate_data.csv", 'w') 
writer = csv.DictWriter(result, fieldnames, extrasaction='ignore') 
for d in dict_filter(reader, fieldnames):
    if d['_STATE'] == "17" : 
         writer.writerow(str(d))

这是我在终端中遇到的错误:

AttributeError: 'str' object has no attribute 'get' 

在TextWrangler中:

Traceback (most recent call last): writer.writerow(str(d))

我看了整个互联网,并没有找到任何缓解。为什么writerow无法处理我的DictWriter实例?

1 个答案:

答案 0 :(得分:1)

更改行

writer.writerow(str(d))

writer.writerow(d)
相关问题