简体   繁体   中英

Writing XY coordinates to CSV file using Python

I'm new to python programming and I have a fairly simple project but am having some difficulties. I would like to (a) extract the XY coordinates of the vertices of a shapefile (polygon) and (2) write all the coordinates into a csv file where the first column has the X coordinates and the second column has the Y coordinates. The code that I've written thus far writes the vertices coordinates to a csv file, but each digit of the coordinate is placed in a different column.

Here is my code so far:

import arcpy, os, csv
from arcpy import env
workspace = "J:/Folder/"
arcpy.env.overwriteOutput = True
myPath = workspace
oFile = open(myPath + "xyCoord.csv", "w")
polygon = myPath + "Polygon2.shp" 
writer = csv.writer(oFile, delimiter = ',', dialect = 'excel', lineterminator = '\n')
writer.writerow(['X', 'Y'])

for row in arcpy.da.SearchCursor(polygon, ["OID@", "SHAPE@"]):
    print ("Feature {0}:".format(row[0]))
    partnum = 0 # Prints the current multipont's ID

    for part in row[1]:
        print ("Part {0}:".format(partnum)) # Prints the part number

        for vertex in part:
            print ("{0}, {1}".format(vertex.X, vertex.Y))
            writer.writerow(str(vertex.X) + str(vertex.Y))
        partnum += 1
        oFile.close()
writer.writerow(str(vertex.X) + str(vertex.Y))

writerow expects an iterable, each element representing a column entry. You are giving it a string, so it interprets it as an iterable, each character being one element and thus one column.

Instead use:

writer.writerow([vertex.X, vertex.Y])

Also you are closing your file in the inner of for and thus you may try to write new lines after the file has been closed.

您必须向writerow传递writerow列表,其中列表中的每个元素都是输出中的单独列:

writer.writerow([vertex.X, vertex.Y])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM