简体   繁体   中英

write specific columns to a csv file with csv module

hi I am trying to write on a csv file using csv module (can't use panda's).

so issue is I am getting keys like this:

name_keys = ['DATASET ID', 'SOURCE NAME', 'NAME']

data = [
   {
      "DATASET ID":112313,
      "SOURCE NAME":"source 1",
      "NAME":"0",
      "TYPE":1,
      "Random":1 
   },
   {
      "DATASET ID":112315,
      "SOURCE NAME":"source 2",
      "NAME":"1",
      "TYPE":1,
      "Random":1 
   }]




with open(file_path, 'w', encoding='UTF8', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=name_keys)
    writer.writerow(name_keys)
    writer.writerows(data_)

so I just want data of required name keys. not all keys in data. how I can achieve this? on this code I am getting error: ValueError: dict contains fields not in fieldnames:

You need to set extrasaction='ignore' as an argument ofDictWriter :

If the dictionary passed to the writerow() method contains a key not found in fieldnames, the optional extrasaction parameter indicates what action to take.

import csv

with open("outputcsv.csv", 'w', encoding='UTF8', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=name_keys,  extrasaction='ignore')
    writer.writeheader()
    writer.writerows(data)

# Output ( .csv ):

在此处输入图像描述

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