I have a csv file with some contents as shown below:
name,x,y
N1,30.2356,12.5263
N2,30.2452,12.5300
...and it goes on.
This is what I tried, I called them from .csv and seperately added to different lists.
import csv
nn = []
xkoor = []
ykoor = []
coord = []
with open('C:/Users/Mert/Desktop/py/transformation/1.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
nn.append(row[0].split(','))
xkoor.append(row[1].split(','))
ykoor.append(row[2].split(','))
j = 1
for i in range(len(xkoor)):
for j in range(len(ykoor)):
I'm trying to make a list as:
coord = [30.2356,12.5263],[30.2452,12.5300],....
and I couldn't understand how to do it. Any ideas?
The csv-reader should split rows for you by commas on default:
import csv
with open('somefile.csv') as fh:
reader = csv.reader(fh)
for row in reader:
print(row)
# outputs
['name', 'x', 'y']
['N1', '30.2356', '12.5263']
['N2', '30.2452', '12.5300 ']
With this in mind, if you are just looking to loop over coords, you can use unpacking to get your x
and y
, then build your list by appending tuples:
import csv
coords = []
with open('somefile.csv') as fh:
reader = csv.reader(fh)
next(reader) # skips the headers
for row in reader:
name, x, y = row
coords.append((float(x), float(y)))
# then you can iterate over that list like so
for x, y in coords:
# do something
Coords will then look like:
[(30.2356, 12.5263), (30.2452, 12.53)]