使用Python将XY坐标写入CSV文件 [英] Writing XY coordinates to CSV file using Python
问题描述
我刚接触python编程,我有一个相当简单的项目,但是有一些困难。我想(a)提取shapefile(多边形)的顶点的XY坐标和(2)将所有坐标写入csv文件,其中第一列具有X坐标,第二列具有Y坐标。我写的代码到目前为止将顶点坐标写入一个csv文件,但每个数字的坐标放在一个不同的列。
这里是我的代码到目前为止:
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 ='\\\
')
writer.writerow(['X', 'y'])
用于arcpy.da.SearchCursor(polygon,[OID @,SHAPE @])中的行:
print(Feature {0}: .format(row [0]))
partnum = 0#为行[1]中的部分打印当前multipont的ID
:
print(Part {0} .format(partnum))#在零件中为顶点打印零件号
:
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
期望可迭代,每个元素表示列条目。
请改用:
writer.writerow([vertex.X,vertex.Y])
此外,您在
的内部关闭您的文件
,因此您可以尝试在文件关闭后写入新行。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.这篇关于使用Python将XY坐标写入CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!