Home > Enterprise >  write specific columns to a csv file with csv module
write specific columns to a csv file with csv module

Time:11-26

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:

CodePudding user response:

You need to set extrasaction='ignore' as an argument of enter image description here

  • Related