2
使用Internet上的一些帮助,我构建了一个通用函数,它从csv文件中提取特定列并将其读取到输入键指定的字典中。为什么DictWriter不能在我的代码中工作?
import csv
def dict_filter(it, keys):
for d in it:
yield dict((k, d[k]) for k in keys)
然后我后来把这种方法用DictReader
和DictWriter
写这些列到另一个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实例?
这是整个错误?这是令人惊讶的。之后没有一条线? – 2012-08-10 05:27:23
是的,我在TextWrangler中运行它,并且之后没有任何行。 – SVenkatesh 2012-08-10 05:31:09
编辑解释了很多。尝试将该行更改为'writer.writerow(d)'。 – 2012-08-10 05:34:05