我想解析一个csv文件,在Field3中查找没有任何“/”的单元格,并将这些单元格复制到fieldoutput行的output.csv文件中。
我尝试了以下代码,但是我收到了这个错误:
Traceback (most recent call last):
File "<string>", line 13, in <module>
File "C:\Python27\ArcGIS10.1\Lib\csv.py", line 148, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "C:\Python27\ArcGIS10.1\Lib\csv.py", line 144, in _dict_to_list
", ".join(wrong_fields))
ValueError: dict contains fields not in fieldnames: Field1, Field2, Field3, Field4
这是我的代码:
import csv
f = open("C:\My\Path\file.csv", "r")
reader = csv.DictReader(f, delimiter=';')
writer = open("C:\My\Path\output.csv",'wb')
output = csv.DictWriter(writer, 'fieldoutput', delimiter=';')
print output
for row in reader:
if '/' not in row['Field3'] :
#print row['Field3']
output.writerow(row)
感谢您的帮助!
答案 0 :(得分:1)
我认为您没有正确指定第二个DictWriter
参数。由于您正在编写的行是字典,DictWriter
需要知道如何订购字段:
fieldnames参数是一系列键,用于标识传递给writerow()方法的字典中的值被写入csvfile的顺序。
尝试从此处更改DictWriter初始化:
output = csv.DictWriter(writer, 'fieldoutput', delimiter=';')
到此:
output = csv.DictWriter(writer, fieldnames=reader.fieldnames, delimiter=';')