Reputation: 323
I'm writing a python code to read the points in a polygon shape-file and save them in a point shape file.
So first I made a text file and stored the points' (x,y) in that .txt file. then I tried to make a point shape-file from the text file but it gave an error.
here is the code (just the last part):
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
Here is the error:
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
Upvotes: 7
Views: 7557
Reputation: 363
Here is an alternative solution. It reads in a tab-delineated .ascii file (which is very similar to a .txt file) which it assumes has headers of Longitude and Latitude. I came across this question and then ended up with this solution so I figured that it can probably help someone.
# ------------------------------------------------------
# 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)
})
Upvotes: 1
Reputation: 3459
have you tried calling float(X), float(Y) as maybe its doesn't like strings?
If you can get your input into a numpy array, you can convert that to a feature class in one step:
http://arcpy.wordpress.com/2012/09/14/building-feature-classes-from-numpy-arrays/
Upvotes: 1