【发布时间】:2017-04-29 14:51:58
【问题描述】:
名为 Sample.csv 的 CSV 测试文件包含:
Brand, Price, Weight, Type
brand1, 6.05, 3.2, orange
brand2, 8.05, 5.2, orange
brand3, 6.54, 4.2, orange
brand1, 6.05, 3.2, pear
brand2, 7.05, 3.6, pear
brand3, 7.45, 3.9, pear
brand1, 5.45, 2.7, apple
brand2, 6.05, 3.2, apple
brand3, 6.43, 3.5, apple
brand4, 7.05, 3.9, apple
brand1, 8.05, 4.2, plum
brand2, 3.05, 2.2, plum
我的代码是:
import csv
headers = ['Brand','Price','Type']
with open('sample.csv', newline='') as rf:
reader = csv.DictReader(rf, delimiter=',',fieldnames=headers)
with open('output.csv', 'w', newline='') as wf:
writer = csv.DictWriter(wf, delimiter=',', extrasaction='ignore', fieldnames=headers)
writer.writerow(dict((fn,fn) for fn in writer.fieldnames))
for row in reader:
print(row)
writer.writerow(row)
我只是想将品牌、价格、类型输入输出文件,但我得到:
Brand,Price,Type
Brand, Price, Weight
brand1, 6.05, 3.2
brand2, 8.05, 5.2
brand3, 6.54, 4.2
brand1, 6.05, 3.2
brand2, 7.05, 3.6
brand3, 7.45, 3.9
brand1, 5.45, 2.7
brand2, 6.05, 3.2
brand3, 6.43, 3.5
brand4, 7.05, 3.9
brand1, 8.05, 4.2
brand2, 3.05, 2.2
为什么我在输出中得到的是权重字段,而不是类型字段?
请注意,添加了行 writer.writerow(dict((fn,fn) for fn in writer.fieldnames)) 用于调试,有意打印出标题两次。
【问题讨论】:
-
如果我们看到输入文件的一小部分样本,我们将更有能力提供帮助——小到足以重现问题而不会产生过多的负担。
-
输入文件,sample.csv显示在顶部。