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.