6

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!

V22
  • 157
  • 1
  • 2
  • 11

5 Answers5

5

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))
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
2

You're almost there, do this:

with open('lat_lon', 'w') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    for la, lo in zip(lat, lon):
        writer.writerow([la, lo])

Or more concise (as pointed out above):

with open('lat_lon', 'w') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    writer.writerows(zip(lat, lon))
DevShark
  • 8,558
  • 9
  • 32
  • 56
1
import pandas as pd
lat = [34.78, 34.82, 34.86, 34.92]
lon = [-86.02, -86.06, -86.10, -86.14]

output = pd.DataFrame(lat, columns=['lat'])
output['lon'] = lon
output.to_csv('lat_lon', index=False)
dark
  • 256
  • 2
  • 12
0

The key point is zip(lat, lon). You can make the above answers more compact like this.

import csv
with open('lat_lon', 'w') as csvfile:
    csv.writer(csvfile).writerows(zip(lat, lon))
Hun
  • 3,707
  • 2
  • 15
  • 15
0

Please try this readymade example:

import csv
fileName = './fileName.csv' # modify both file name and path if required
def WriteToCSV(fileName, col_1, col_2, col_3):
    row = [col_1, col_2, col_3]
    with open(fileName, 'a', newline='') as f:  # create and/ or opening the csv file in append mode
        writer = csv.writer(f)
        writer.writerow(row)


col_1 = 'col_1'
col_2 = 'col_2'
col_3 = 'col_3'
WriteToCSV(fileName, col_1, col_2, col_3) # calling the function 

Good luck.

Pawan Kumar
  • 114
  • 9