3

I have a txt file like this:

Point
0 347172.2 4269952.7 60.9090909091
1 337172.8 4278952.4 85.7334909091
2 344572.3 4547952.2 123.909673091
3 347532.8 8777952.8 456.467809091
END

The third column are some values i want to have in my points.shp. I wrote this script but it doesn't seem to work, meaning it doesn't pass the specific values of the third column

import arcgisscripting
gp = arcgisscripting.create()
# Set up inputs to tool
inTxt = arcpy.GetParameterAsText(0)
inSep = "."
strms = arcpy.GetParameterAsText(1)
# Run tool
gp.CreateFeaturesFromTextFile(inTxt, inSep, strms, "#")

What should i add also? I am using ArcGIS 10.2

  • When you run your code snippet as a test what values do you use for inTxt and strms? What error or other symptom is seen when you run that? Please use the edit button to provide a more detailed description of what you have tried and where you are stuck. I wondered what your last line was about and found resources.arcgis.com/en/help/main/10.2/index.html#//… - linking to help associated with any lesser known functions that you are using can be a good way to help potential answerers help you. – PolyGeo May 31 '15 at 21:49
  • i made a copy of this code and used it here. The result i get is actually the x,y coordinates but not the last value – por.bet Jun 1 '15 at 2:25
  • According to the documentation for that sample tool it does not process more than the coordinates and "This tool has been deprecated" so I think you would be better using the approach advocated by @Aaron anyway. – PolyGeo Jun 1 '15 at 2:45
  • so should i delete Point and End and make the rest of the data seem like for example for the first line: [('60.9090909091', ('347172.2', '4269952.7'))] ?? – por.bet Jun 1 '15 at 2:48
  • can you provide an example of how you would use the newGeom.projectAs in this case to re-project the points from the input SR into OSGB (EPSG 27700)? I am writing more or less the same script but would like to take my input points (in WGS1984) and re-project them into OSGB (EPSG 27700) before inserting into a blank point shapefile. Many Thanks – Philip Muggeridge Jun 17 '16 at 14:44
5

Here is one approach that utilizes an Insert Cursor to directly insert the coords into the SHAPE@XY slot.

import arcpy, os

# Read txt file
tmp = [line.split() for line in open(r'C:\temp\txtfile.txt')]

"""
Clean txt file and prepare for Insert Cursor
Needs to be in the following format for this example:
[('60.9090909091', ('347172.2', '4269952.7')),
 ('85.7334909091', ('337172.8', '4278952.4')),
 ('123.909673091', ('344572.3', '4547952.2')),
 ('456.467809091', ('347532.8', '8777952.8'))]
"""
row_values = []
for t in tmp:
    row_values.append((float(t[3]), (float(t[1]), float(t[2]))))

# Define the shapefile
shp = r'C:\temp\points.shp'

# Define spatial reference and create shapefile.  Factory code for NAD83 UTM 15N is used here
sr = arcpy.SpatialReference(26915)
arcpy.CreateFeatureclass_management (out_path = os.path.dirname(shp), out_name = os.path.basename(shp), geometry_type = "POINT", spatial_reference = sr)
arcpy.AddField_management(shp, "Field1", "DOUBLE")

# Use InsertCursor to update rows
cursor = arcpy.da.InsertCursor(shp, ['Field1','SHAPE@XY'])

for row in row_values:
    cursor.insertRow(row)

# Clean up
del cursor
  • i made my line from this Point 0 347172.2 4269952.7 60.9090909091 END to this [('60.9090909091', ('347172.5', '4277952.5')) BUT i get a parsing error at line 16: Runtime error Traceback (most recent call last): File "<string>", line 16, in <module> IndexError: list index out of range – por.bet Jun 1 '15 at 2:38
  • yes i know, i am testing it for points but it doen't work amd returns an error: Runtime error Traceback (most recent call last): File "<string>", line 16, in <module> IndexError: list index out of range – por.bet Jun 1 '15 at 2:49
  • 1
    Ignore my previous comment, for this to work you need to have your input data in the exact format that @Aaron specifies in the comment near the beginning of his code. If your format is different then the code will need to be modified to work with it. – PolyGeo Jun 1 '15 at 2:54
  • 2
    Please be aware that @Aaron has offered an approach, and that GIS SE uses a focussed Q&A format i.e. it does not offer a code writing/debugging service. – PolyGeo Jun 1 '15 at 2:58
  • @por.bet I suspect that you need make sure your txt file does not contain the words "Point" and "END" at the beginning and end of the txt file. For this example, I copied your test data to a txt file (without "Point" and "END") and used that as the input data during testing. – Aaron Jun 1 '15 at 11:24
2

Rather that getting the user to change the order/style of the points it would be best to change the code to suit the input.. I would imagine when you need to write a script to import points you'd have a lot of them..

I would try to split the lines using string.split and if I tried a few possible delimiters and still ended up with a list of 1 then skip the line:

Point <- skip, only one element
0 347172.2 4269952.7 60.9090909091 <- do this one, 4 elements
1 337172.8 4278952.4 85.7334909091 <- do this one, 4 elements
2 344572.3 4547952.2 123.909673091 <- do this one, 4 elements
3 347532.8 8777952.8 456.467809091 <- do this one, 4 elements
END <- skip, only one element

This is fairly easy to code for:

import os, sys, arcpy

InFile = sys.argv[1]
OutShp = sys.argv[2]
EPSG   = sys.argv[3]

try:
    SR = arcpy.SpatialReference(int(EPSG))# create a spatial reference from EPSG definition
except:
    arcpy.AddWarning(arcpy.GetMessages())
    arcpy.AddError("Unable to create spatial reference with code %s" % EPSG)
    sys.exit(0)

#break up OutShp to folder and name
OutFolder = os.path.dirname(OutShp)
OutName   = os.path.basename(OutShp)

# Create the output feature class
arcpy.CreateFeatureclass_management(OutFolder,OutName,"POINT",has_z="ENABLED",spatial_reference=SR)
# add fields to store the values
arcpy.AddField_management(OutShp,"PntID","INTEGER")
arcpy.AddField_management(OutShp,"Xcoord","DOUBLE")
arcpy.AddField_management(OutShp,"Ycoord","DOUBLE")
arcpy.AddField_management(OutShp,"Zcoord","DOUBLE")

with open(InFile,'r') as srcFile:
    with arcpy.da.InsertCursor(OutShp,["SHAPE@","PntID","Xcoord","Ycoord","Zcoord"]) as InsCur:
        for fileLine in srcFile:
            # split the line up into a list
            # 1 337172.8 4278952.4 85.7334909091 becomes [1,337172.8,4278952.4,85.7334909091]
            # try a few common delimiters: tab, space, comma, pipe..
            lSplit = fileLine.split("\t")
            if len(lSplit) == 1:
                lSplit = fileLine.split(" ")
            if len(lSplit) == 1:
                lSplit = fileLine.split(",")
            if len(lSplit) == 1:
                lSplit = fileLine.split("|")

            if len(lSplit) > 1:
                # more than just one word on the line
                pointsOK = True
                try:
                    ID     = int(lSplit[0])
                    Xcoord = float(lSplit[1])
                    Ycoord = float(lSplit[2])
                    Zcoord = float(lSplit[3])
                except:
                    arcpy.AddWarning("Unable to translate points")
                    pointsOK = False

                if pointsOK:
                    # create a point geometry from the 3 coordinates
                    newGeom  = arcpy.PointGeometry(arcpy.Point(Xcoord,Ycoord,Zcoord))
                    newGeom.spatial_reference = SR # set spatial reference
                    # you could project here using newGeom.projectAs(SpatialRef)
                    # if you needed them in a different spatial reference                        
                    InsCur.insertRow([newGeom,ID,Xcoord,Ycoord,Zcoord])# insert this point into the feature class

Arcpy insert cursor (arcpy.da.InsertCursor) does not allow "SHAPE@XYZ", but you can address this using "SHAPE@" and using a geometry object in arcpy. This is especially handy if you have the coordinates in a different spatial reference and need to project on the way in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.