借助互联网的一些帮助,我构建了一个通用函数,该函数从 csv 文件中提取特定列并将其读入字典,由输入 keys 指定。
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 实例上不起作用?
请您参考如下方法:
换行
writer.writerow(str(d))
到
writer.writerow(d)
