Search code examples
pythoncsvkeyerror

Key values of CSV incorrect causing key error


I have csv file from which I am trying to extract a particular column but I get keyerror. When I try to print the keys of the csv, I get this result:

[None, 'Id;"PostTypeId";"ParentId";"AcceptedAnswerId";"OwnerUserId";"LastEditorUserId";"OwnerDisplayName";"LastEditorDisplayName";"UserIdCombined"']

Code I tried:

    read_file = open ("ml_sample_complete.csv","r") # open input file for reading
    col_dict = {}
    with open('out.csv', 'wb') as f: # output csv file
        writer = csv.writer(f)
    with open('ml_sample_complete.csv','r') as csvfile: # input csv file
        reader = csv.DictReader(csvfile, delimiter=',')
        for row in reader:
            print(row.keys())
            print(row["Tags"])
            col_dict.update(row)
    print(col_dict)
    read_file.close()

Please help me understand what is wrong here and how to rectify it.


Solution

  • Are you sure that your delimter should be ',' and not a ';' in the dictreader function.