简体   繁体   中英

Using DictWriter/Reader with csv module in python

I want to parse a csv file, looking in Field3 for cells which dont have any "/" in and copy these cells in a output.csv file in a fieldoutput row.

I tried the following code but i get this error:

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

Here is my code:

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)

Thanks for your help !

I don't think you're specifying the second DictWriter parameter correctly. Since the rows you're writing are dictionaries, DictWriter needs to know how to order the fields:

The fieldnames parameter is a sequence of keys that identify the order in which values in the dictionary passed to the writerow() method are written to the csvfile.

Try changing your DictWriter initialization from this:

output = csv.DictWriter(writer, 'fieldoutput', delimiter=';')

to this:

output = csv.DictWriter(writer, fieldnames=reader.fieldnames, delimiter=';')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM