用重新排列的列写入CSV文件

时间:2018-10-28 18:44:30

标签: python python-3.x csv

我是Python开发的新手,正在尝试写入csv文件。我有一个 in.csv 文件,我需要将其某些列写入 out.csv 。输入的csv具有列“ a,b,c,d,e”,而我只需要重新排列列“ a,d,b”。当我尝试实现此目标时,会引发如下错误。

下面是我的代码:

import csv

fileName = r"D:\in.csv"
out_list = ['a','d','b']
with open(fileName, 'r') as infile, open(r"D:\out.csv",'w+',newline='') as 
outfile:
writer = csv.DictWriter(outfile, fieldnames=out_list)
writer.writeheader()
for row in csv.DictReader(infile):
    # writes the reordered rows to the new file
    writer.writerow(row)

下面是错误消息:

Traceback (most recent call last):
File "D:/test.py", line 11, in <module>
writer.writerow(row)
File 
"C:\Users\Laxmikant\AppData\Local\Programs\Python\Python35\lib\csv.py", 
line 153, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File 
"C:\Users\Laxmikant\AppData\Local\Programs\Python\Python35\lib\csv.py", 
line 149, in _dict_to_list
+ ", ".join([repr(x) for x in wrong_fields]))
ValueError: dict contains fields not in fieldnames: 'e', 'c'

in.csv 中的内容:

a,b,c,d,e  
a1,b1,c1,d1,e1  
a2,b2,c2,d2,e2  
a3,b3,c3,d3,e3  
a4,b4,c4,d4,e4  

1 个答案:

答案 0 :(得分:1)

感谢您的支持,我通过更改来解决了

writer = csv.DictWriter(outfile, fieldnames=out_list)

writer = csv.DictWriter(outfile, fieldnames=out_list, extrasaction ='ignore')

添加

extrasaction ='ignore'

已解决的问题。