Home > Back-end >  Writing a CSV with multiple variables with fieldnames python
Writing a CSV with multiple variables with fieldnames python

Time:04-20

Im very new to python so please be kind... I need to write a csv file with multiple variables and a fieldname. I found a different post: Writing a CSV with multiple variables

But i have 0 clue how to add a fieldname. I know that it has to be something like:

with open('lat_lon', 'w') as csvfile:
    fieldnames = ['lat','lon']
    writer=csv.writer(csvfile, delimiter=',',fieldnames=fieldnames)
    writer.writeheader
    writer.writerows(zip(lat, long)

if you can help me that would be great!

btw I'm using python 3.10.4 and pycharm community edition 2021.3.3 on mac.

Thanks!

CodePudding user response:

Field names in a csv file are no more than the first row of that file. So at the beginning you can simply write a row with the desired field names in your csv file:

import csv

with open('lat_lon.csv', 'w') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    writer.writerow(['lat', 'lon'])
    # ...
  • Related