Arcpy InsertCursor Issue

1700
9
02-08-2019 01:23 PM
JosephTapanes
New Contributor

Hey all,

I have some text files with x,y coordinates in them. I created a script that finds the specific .txt files that I want and then puts them in a list. Then it creates corresponding EMPTY feature classes for them. I'm trying to use an insertcursor to populate the empty feature classes with the contents of the text files. However, I'm stuck on this part. Here is the portion of my script that is not working:

# puts the empty feature classes in a list.

fclist = arcpy.ListFeatureClasses()

for fc in fclist:
      cursor = arcpy.da.InsertCursor(fc, ["SHAPE@"])
      array = arcpy.Array()

#text_Points is the list of the txt files.

      for file in text_Points:
            desc = arcpy.Describe(file)
            desc1 = arcpy.Describe(fc)
            if desc.basename == desc1.basename:
                print "yes"
                for line in fileinput.input(file):
                     ID, X, Y = string.split(line, " ")
                     array.add(arcpy.Point(X, Y))
                     cursor.insertRow([arcpy.Point(array)])
                     fileinput.close()
                     del cursor
            else:
               print "error"

I'm grateful for any pointers. Thanks.

0 Kudos
9 Replies
JosephTapanes
New Contributor

Here's the code in the syntax highlighter.

fclist = arcpy.ListFeatureClasses()



for fc in fclist:
    cursor = arcpy.da.InsertCursor(fc, ["SHAPE@XY"])
    array = arcpy.Array()
    for file in text_Points:
        desc = arcpy.Describe(file)
        desc1 = arcpy.Describe(fc)
        if desc.basename == desc1.basename:
            print "yes"
            for line in fileinput.input(file):
                ID, X, Y = string.split(line, " ")
                array.add(arcpy.Point(X, Y))
                cursor.insertRow([arcpy.Point(array)])
                fileinput.close()
                del cursor
        else:
            print "error"
0 Kudos
DanPatterson_Retired
MVP Emeritus

cursors may not be needed if your table is in the correct form and you want a point file with attributes

Make XY Event Layer—Data Management toolbox | ArcGIS Desktop 

either use the tool, or steal from the code snippet... I am sure it is one big cursor-ish function behind it all

JosephTapanes
New Contributor

Dan, thanks for the response. Really appreciate it!

Unfortunately, ESRI did not include that tool as a script tool, so I can't right-click and select edit to open the code. My guess is that the issue might have something to do with the InsertCursor within the for loop. Out of all the documentation on the InsertCursor, I have never seen an instance where the InsertCursor was within a for loop.

0 Kudos
DanPatterson_Retired
MVP Emeritus

you missed my point about seeing the code snippet at the end of the link I sent.

Modifying what is there...

# Description: Creates an XY layer and exports it to a layer file

# import system modules and Set environment settings
import arcpy
arcpy.env.workspace = "C:/data"    # ---- your folder containing the file
 
# Set the local variables
in_Table = "your.txt"      # ---- your csv or txt or dbas file
x_coords = "X"             # ---- what field is x
y_coords = "Y"             # ---- ditto for y
out_Layer = "event_layer"  # ---- give it featureclass name
saved_Layer = r"C:/data/your.lyr"  # ---- a layer file is cool

# Set the spatial reference  # ---- if you know it and/or have a *.prj file or equivalent
spRef = r"Coordinate Systems\Projected Coordinate Systems\Utm\Nad 1983\NAD 1983 UTM Zone 11N.prj"

# XY event layer magic... 
arcpy.MakeXYEventLayer_management(in_Table, x_coords, y_coords, out_Layer, spRef)

# Save to a layer file  #
arcpy.SaveToLayerFile_management(out_Layer, saved_Layer)
JosephTapanes
New Contributor

Oh gotcha. I would love to use that tool in arcpy, but it's for an assignment and we can only use the insertcursor.

0 Kudos
DanPatterson_Retired
MVP Emeritus

Darn Profs... we are mean aren't we

0 Kudos
RandyBurton
MVP Alum

Sounds like you've got reading text files worked out.  Since it's for an assignment, this thread Reprojecting tabular data without creating feature class might be of interest.  In one of my comments, I shared a bit of code that takes a list of xy coordinates and uses an insert cursor to make a table.  It could give you some ideas.  And another old thread: geometry help w/ da.InsertCursor.

JosephTapanes
New Contributor

Thanks Randy! Very helpful.

0 Kudos
JosephTapanes
New Contributor

I figured it out:

# import libraries
import arcpy
import os
import string
import fileinput
from arcpy import env
env.overwriteOutput = True
env.workspace = "D:/JHU/Spring_2019/Python_Scripting/Labs/Lab_3/Lab3/GPS_Results.gdb/Study_Areas/"

# create the empty lists to hold all of the text files and to hold the textfiles that have the keyword in them

text_all = []
text_Points = []
keyword = "POINT_X"
iterate_start = r"D:\JHU"



# Use os.walk to iterate through the folders and append txt files to the empty list.

for path, dirs, files in os.walk(iterate_start):
    for f in files:
        if f.endswith(".txt"):
            text_all.append(os.path.join(path, f))




# Use more for loops to refine the list of txt files. Only include txt files with the keyword in them and append to the other empty list.
                          
for doc in text_all:
    desc = arcpy.Describe(doc)
    if arcpy.Exists(doc):
        for field in desc.fields:
            if field.name == keyword:
                text_Points.append(doc)



# Create a new GDB
arcpy.CreateFileGDB_management("D:/JHU/Spring_2019/Python_Scripting/Labs/Lab_3/Lab3", "GPS_Results")

# Create a feature dataset in the new GDB and assign it a spatial reference of UTM Zone 12, NAD83.

sr = arcpy.SpatialReference(26912)

arcpy.CreateFeatureDataset_management("D:/JHU/Spring_2019/Python_Scripting/Labs/Lab_3/Lab3/GPS_Results.gdb", "Study_Areas", sr)

# This for loop creates the empty point feature classes in the feature dataset. It uses an insert cursor to add the coordinates in the txt files to their respective feature classes.

for points in text_Points:
    desc = arcpy.Describe(points)
    arcpy.CreateFeatureclass_management("D:/JHU/Spring_2019/Python_Scripting/Labs/Lab_3/Lab3/GPS_Results.gdb/Study_Areas/", desc.basename, "Point", "", "", "", sr)
    fcname = "D:/JHU/Spring_2019/Python_Scripting/Labs/Lab_3/Lab3/GPS_Results.gdb/Study_Areas/" + desc.basename
    cursor = arcpy.da.InsertCursor(fcname, ["SHAPE@XY"])
    for line in fileinput.input(points):
        if not fileinput.isfirstline():
            ID, X, Y = line.split()
            ptobject = arcpy.Point(X, Y)
            ptGeometry = arcpy.PointGeometry(ptobject)
            cursor.insertRow(ptGeometry)
    fileinput.close()
    del cursor
0 Kudos