Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a CSV with multiple variables

Tags:

python

csv

I currently have two lists:

lat = [34.78, 34.82, 34.86, 34.92]
lon = [-86.02, -86.06, -86.10, -86.14]

I am trying to write a csv file that outputs them as lat/lon:

34.78, -86.02
34.82, -86.06
34.86, -86.10
34.92, -86.14

I tried using:

with open('lat_lon', 'w') as csvfile:
    writer=csv.writer(csvfile, delimiter=',')
    writer.writerow(lat)
    writer.writerow(lon)

But this gives me the lat values all in one row and the lon values in a separate row. Any ideas on how to correct this? Thanks!

like image 654
V22 Avatar asked Mar 27 '16 20:03

V22


1 Answers

You just need to zip and use writerows instead of writerow:

with open('lat_lon', 'w') as csvfile:
    writer=csv.writer(csvfile, delimiter=',')
    writer.writerows(zip(lat, lon))
like image 188
Padraic Cunningham Avatar answered Oct 30 '22 08:10

Padraic Cunningham