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!

0

5 Answers 5

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))
Sign up to request clarification or add additional context in comments.

Comments

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))

2 Comments

You snatched my answer while I was typing it!
Sorry, this happens! :)
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)

Comments

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))

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.