Python:如何从文本文件创建点形状文件

时间:2013-10-03 04:28:43

标签: python polygon arcgis shapefile arcpy

我正在编写一个python代码来读取多边形形状文件中的点并将它们保存在点形状文件中。 所以首先我制作了一个文本文件并将点'(x,y)存储在该.txt文件中。然后我尝试从文本文件中创建一个点形状文件,但是它给出了一个错误 这是代码(只是最后一部分):

creat point shape-file from text file 
import fileinput
import string
import os
env.overwriteOutput=True
outpath="C:/roadpl"
newfc="newpoint.shp" 
arcpy.CreateFeatureclass_management(outpath, newfc, "Point")
infile="C:/roadpl/roadL5.txt"
cursor=arcpy.da.InsertCursor(newfc, ["SHAPE@"])
array=arcpy.Array()
for line in fileinput.input(infile):
    X, Y=string.split(line, " ")
    array.add(arcpy.Point(X,Y))
cursor.insertRow([arcpy.Point(array)])
fileinput.close()
del cursor

这是错误:

Traceback (most recent call last):
  File "C:\Lab5\P_Code_L5", line 49, in <module>
    point.X, point.Y  = line.split()
  File "C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy\arcpy\arcobjects\_base.py", line 87, in _set
    return setattr(self._arc_object, attr_name, cval(val))
RuntimeError: Point: Input value is not numeric

2 个答案:

答案 0 :(得分:1)

您是否尝试过调用float(X),float(Y),因为它可能不喜欢字符串?

如果您可以将输入变为numpy数组,则可以一步将其转换为要素类:

http://arcpy.wordpress.com/2012/09/14/building-feature-classes-from-numpy-arrays/

答案 1 :(得分:1)

这里是替代解决方案。它读取一个制表符描述的.ascii文件(与.txt文件非常相似),并假定该文件具有经度和纬度标头。我遇到了这个问题,然后提出了这个解决方案,所以我认为它可能可以帮助某人。

# ------------------------------------------------------
# IMPORTS
# ------------------------------------------------------

import os
import pandas as pd
from shapely.geometry import Point, mapping
from fiona import collection

# ------------------------------------------------------
# INPUTS
# ------------------------------------------------------

# Define path
path = os.path.abspath(os.path.dirname(__file__))

# Set working directory
os.chdir(path)  

# Define file to convert
file = 'points.ascii'

# Define shp file schema
schema = { 'geometry': 'Point', 'properties': { 'LocationID': 'str', 'Latitude': 'float', 'Longitude': 'float' } }

# Read in data
data = pd.read_csv(file, sep='\t') 

# Define shp file to write to
shpOut = 'points.shp'

# Create shp file
with collection(shpOut, "w", "ESRI Shapefile", schema) as output:
    # Loop through dataframe and populate shp file
    for index, row in data.iterrows():
        
        # Define point
        point = Point(row['Longitude'], row['Latitude'])
        # Write output
        output.write({
            'properties': {'LocationID': row['LocationID'], 'Latitude': row['Latitude'], 'Longitude': row['Longitude'] }, 
            'geometry': mapping(point)
        })