I have a JSON file of Latitude/Longitude that I want to covert to a CSV file. I want to do this using Python. I have read/tried all other stackoverflow and google search results
I would use a csv.DictWriter, since you're dealing with dicts, which is exactly the case DictWriter
is there for.
rows = json.loads(x)
with open('test.csv', 'wb+') as f:
dict_writer = csv.DictWriter(f, fieldnames=['longitude', 'latitude'])
dict_writer.writeheader()
dict_writer.writerows(rows)
Edit:
Since the .writeheader()
method was only added in 2.7, you can use something like this on older versions:
rows = json.loads(x)
fieldnames = ['longitude', 'latitude']
with open('test.csv', 'wb+') as f:
dict_writer = csv.DictWriter(f, fieldnames=fieldnames)
dict_writer.writerow(dict(zip(fieldnames, fieldnames)))
dict_writer.writerows(rows)