write specific columns to a csv file with csv module

Question:

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:

Asked By: tousif Noor

||

Answers:

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

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) :

enter image description here

Answered By: abokey
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.