使用 Python 将 XY 坐标写入 CSV 文件 [英] Writing XY coordinates to CSV file using Python
问题描述
我是 Python 编程的新手,我有一个相当简单的项目,但遇到了一些困难.我想(a)提取shapefile(多边形)顶点的XY坐标和(2)将所有坐标写入一个csv文件,其中第一列具有X坐标,第二列具有Y坐标.到目前为止,我编写的代码将顶点坐标写入 csv 文件,但坐标的每个数字都放在不同的列中.
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.
这是我目前的代码:
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
需要一个可迭代的,每个元素代表一个列条目.你给它一个字符串,所以它把它解释为一个可迭代的,每个字符都是一个元素,因此是一列.
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.
改为使用:
writer.writerow([vertex.X, vertex.Y])
此外,您正在 for
的内部关闭文件,因此您可能会在文件关闭后尝试编写新行.
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.
这篇关于使用 Python 将 XY 坐标写入 CSV 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!