Search code examples
pythoncsvqgis

How do I read coordinates from a csv file into Python?


I am trying to read the coordinates from a csv file in order to perform clustering with this data. I am struggling to correctly read the coordinates. This is the code I have tried so far:

with open('buildingpoints.csv') as file:
     data = [(X, Y) for X, Y in csv.reader(file)]
    for row in data
        print(row)

I have attached a screenshot of the csv file from which I am trying to extract the information. Any help would be appreciated

csv file with coordinates


Solution

  • Update: add more explanation


    csv.reader return a iterator, if you iterate it, it yields one row(list, splited by delimeter) per loop.

    your problem is there are too many values(columns) to unpack, X, Y is not enough to contain all the values in one row.

    csv.DictReader do almost same with csv.reader but yield a dictionary-based row instead of list-based row. So you can access field with field name.

    more detail in python csv documentation

    use csv.DictReader

    import csv
    
    with open('buildingpoints.csv') as file:
        reader = csv.DictReader(file)
        for row in reader:
            print(row['X'], row['Y'])