Search code examples
pythonlistcsvgeo

Create single CSV from two CSV files with X and Y values in python


I have two CSV files; one containing X(longitude) and the other Y(latitude) values (they are 'float' data type)

I am trying to create a single CSV with all possible combinations (e.g. X1,Y1; X1, Y2; X1,Y3; X2,Y1; X2,Y2; X2,Y3... etc)

I have written the following which partly works. However the CSV file created has lines in between values and i also get the values stored like this with there list parentheses ['20.7599'] ['135.9028']. What I need is 20.7599, 135.9028

import csv

inLatCSV = r"C:\data\Lat.csv"
inLongCSV = r"C:\data\Long.csv"
outCSV = r"C:\data\LatLong.csv"

with open(inLatCSV, 'r') as f:
  reader = csv.reader(f)
  list_Lat = list(reader)

with open(inLongCSV, 'r') as f:
   reader = csv.reader(f)
   list_Long = list(reader)

with open(outCSV, 'w') as myfile:
   for y in list_Lat:
       for x in list_Long:
            combVal = (y,x)
            #print (combVal)
            wr = csv.writer(myfile)
            wr.writerow(combVal)

Solution

  • Adding a argument to the open function made the difference:

    with open(my_csv, 'w', newline="") as myfile:
        combinations = [[y,x] for y in list_Lat for x in list_Long]
        wr = csv.writer(myfile)
        wr.writerows(combinations)