Skip to content

Instantly share code, notes, and snippets.

@kf0jvt
Created October 28, 2013 17:22
Show Gist options
  • Save kf0jvt/7200902 to your computer and use it in GitHub Desktop.
Save kf0jvt/7200902 to your computer and use it in GitHub Desktop.
How to use csv.DictReader even when you're dealing with shitty data and header row names are duplicated. First you have to make an array of unique header names and tell the DictReader to use that instead of the first row of the file.
anus = reader(open('bullshit_file.csv','rU'))
fieldnames = []
# Read the first row of the csv file and put all the values into a list. Duplicates will not be overwritten.
for headername in anus.next():
if headername not in fieldnames:
fieldnames.append(headername)
else:
fieldnames.append(headername + " Other")
# Now feed that list of unique header names into the DictReader along with the shitty file.
infile = csv.DictReader(open('bullshit_file','rU'),fieldnames=fieldnames)
@krmaxwell
Copy link

Do the names only recur one time each? Otherwise they will end up having the same issue n-1 times.

@kf0jvt
Copy link
Author

kf0jvt commented Oct 28, 2013

I'm pretty sure they do. Not all names recur. Of the ones that do, a third occurrence of a name would become "name Other Other"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment