0
import csv

with open('file.csv', 'r') as file:
    csv_reader = csv.DictReader(file)

    with open('new_file.csv','w') as new_file:
        fieldnames = ['timestamp','src-user','dst-user']

        csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames, delimiter='\t')

        csv_writer.writeheader()

        for line in csv_reader:
            csv_writer.writerow(line)

I wrote this code to create new csv file from old one with appending to it when i tried to write it as dictionary it shows me this error ValueError: dict contains fields not in fieldnames: 'timestamp'

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Ahmad
  • 1
  • 1
  • It is probably because the names of the columns in csv do not match to the fieldbames that you have provided. Can you add the first line of csv to the answer? – Raj Kumar May 17 '20 at 05:13
  • Also this might help you - https://stackoverflow.com/questions/26944274/valueerror-dict-contains-fields-not-in-fieldnames – Raj Kumar May 17 '20 at 05:14
  • It looks like there might be some corruption or garbage at the beginning of your csv file as well, since the field still has timestamp eventually – Cireo May 17 '20 at 05:15
  • Try this, [replace non-ascii characters](https://stackoverflow.com/questions/20078816/replace-non-ascii-characters-with-a-single-space) – sushanth May 17 '20 at 05:17
  • It's not corruption; it's a byte-order mark encoded in UTF-8. – Karl Knechtel May 17 '20 at 05:57
  • @RajKumar can you give me your email to contact you please – Ahmad May 17 '20 at 13:42

0 Answers0