Inserting rows with InsertCursor

You can insert a row into a table or feature class using an InsertCursor object. If you want to insert attribute values along with the new row, you'll need to supply the values in the order found in the attribute table.

Getting ready

The InsertCursor() function is used to create an InsertCursor object that allows you to programmatically add new records to feature classes and tables. The insertRow() method on the InsertCursor object adds the row. A row, in the form of a list or tuple, is passed into the insertRow() method. The values in the list must correspond to the field values defined when the InsertCursor object was created. Just as with the other types of cursors, you can also limit the field names returned using the second parameter of the method. This function supports geometry tokens as well.

The following code example illustrates how you can use InsertCursor to insert new rows into a feature class. Here, we are inserting two new wildfire points into the California feature class. The row values to be inserted are defined in a list variable. Then, an InsertCursor object is created, passing in the feature class and fields. Finally, the new rows are inserted into the feature class using the insertRow() method:

rowValues = [{'Bastrop','N',3000,(-105.345,32.234)),('Ft Davis','N', 456, (-109.456,33.468))]
fc = "c:/data/wildfires.gdb/California"
fields["FIRE_NAME", "FIRE_CONTAINED", "ACRES", "SHAPE@XY"]
with arcpy.da.InsertCursor(fc, fields) as cursor:
  for row in rowValues:
    cursor.insertRow(row)

In this recipe, you will use InsertCursor to add wildfires retrieved from a text file into a point feature class. When inserting rows into a feature class, you will need to know how to add the geometric representation of a feature into the feature class. This can be accomplished using InsertCursor along with two miscellaneous objects: Array and Point. In this exercise, we will add point features in the form of wildfire incidents to an empty point feature class. In addition, you will use Python file manipulation techniques to read the coordinate data from a text file.

How to do it…

We will be importing North American wildland fire incident data from a single day in October, 2007. This data is contained in a comma-delimited text file containing one line for each fire incident on that particular day. Each fire incident has a latitude/longitude coordinate pair separated by commas along with a confidence value. This data was derived by automated methods that use remote sensing data to derive the presence or absence of a wildfire. Confidence values can range from 0 to 100. Higher numbers represent a greater confidence that this is indeed a wildfire:

  1. Open the file at c:ArcpyBookCh9Wildfire DataNorthAmericaWildfire_2007275.txt and examine the contents.

    You will notice that this is a simple comma-delimited text file containing longitude and latitude values for each fire along with a confidence value. We will use Python to read the contents of this file line-by-line and insert new point features into the FireIncidents feature class located in the c:ArcpyBookCh9 WildfireDataWildlandFires.mdb personal geodatabase.

  2. Close the file.
  3. Open ArcCatalog.
  4. Navigate to c:ArcpyBookCh9WildfireData.

    You should see a personal geodatabase called WildlandFires. Open this geodatabase and you will see a point feature class called FireIncidents. Right now this is an empty feature class. We will add features by reading the text file you examined earlier and inserting points.

  5. Right-click on FireIncidents and select Properties.
  6. Click on the Fields tab.

    The latitude/longitude values found in the file we examined earlier will be imported into the SHAPE field and the confidence values will be written to the CONFIDENCEVALUE field.

  7. Open IDLE and create a new script.
  8. Save the script to c:ArcpyBookCh9InsertWildfires.py.
  9. Import the arcpy and os modules:
    import arcpy,os
  10. Set the workspace:
    arcpy.env.workspace = "C:/ArcpyBook/Ch9/WildfireData/WildlandFires.mdb"
  11. Open the text file and read all the lines into a list:
    f = open("C:/ArcpyBook/Ch9/WildfireData/NorthAmericaWildfires_2007275.txt","r")
    lstFires = f.readlines()
  12. Start a try block:
    try:
  13. Create an InsertCursor object using a with block. Make sure you indent inside the try statement. The cursor will be created on the FireIncidents feature class:
    with da.InsertCursor("FireIncidents",("SHAPE@XY","CONFIDENCEVALUE")) as cur:
  14. Create a counter variable that will be used to print the progress of the script:
    cntr = 1
  15. Loop through the text file line by line using a for loop. Since the text file is comma-delimited, we'll use the Python split() function to separate each value into a list variable called vals. We'll then pull out the individual latitude, longitude, and confidence value items and assign them to variables. Finally, we'll place these values into a list variable called rowValue, which is then passed into the insertRow() function for the InsertCursor object, and then we'll print a message:
    for fire in lstFires:
          if 'Latitude' in fire:
            continue
          vals = fire.split(",")
          latitude = float(vals[0])
          longitude = float(vals[1])
          confid = int(vals[2])
          rowValue = [(latitude,longitude),confid]
          cur.insertRow(rowValue)
          print "Record number " + str(cntr) + " written to feature class"
          #arcpy.AddMessage("Record number" + str(cntr) + " written to feature class")
          cntr = cntr + 1
  16. Add the except block to print any errors that may occur:
    except Exception as e:
      print e.message
  17. Add a finally block to close the text file:
    finally:
      f.close()
  18. The entire script should appear as follows:
    import arcpy, os
    
    arcpy.env.workspace = "C:/ArcpyBook/Ch9/WildfireData/WildlandFires.mdb"
    f = open("C:/ArcpyBook/Ch9/WildfireData/NorthAmericaWildfires_2007275.txt","r")
    lstFires = f.readlines()
    try:
      with da.InsertCursor("FireIncidents",("SHAPE@XY","CONFIDENCEVALUE")) as cur:
        cntr = 1
        for fire in lstFires:
          if 'Latitude' in fire:
            continue
          vals = fire.split(",")
          latitude = float(vals[0])
          longitude = float(vals[1])
          confid = int(vals[2])
          rowValue = [(latitude,longitude),confid]
          cur.insertRow(rowValue)
          print "Record number " + str(cntr) + " written to feature class"
          #arcpy.AddMessage("Record number" + str(cntr) + " written to feature class")
          cntr = cntr + 1
    except Exception as e:
      print e.message
    finally:
      f.close()
  19. Save and run the script. You should see messages being written to the output window as the script runs:
    Record number: 406 written to feature class
    Record number: 407 written to feature class
    Record number: 408 written to feature class
    Record number: 409 written to feature class
    Record number: 410 written to feature class
    Record number: 411 written to feature class
    
  20. Open ArcMap and add the FireIncidents feature class to the table of contents. The points should be visible, as shown in the following screenshot:
    How to do it…

How it works…

Some additional explanation may be needed here. The lstFires variable contains a list of all the wildfires that were contained in the comma-delimited text file. The for statement will loop through each of these records one by one, inserting each individual record into the fire variable. We also include an if statement that is used to skip the first record in the file, which serves as the header. As I explained earlier, we then pull out the individual latitude, longitude, and confidence value items from the vals variable, which is just a Python list object and assign them to variables called latitude, longitude, and confid. We then place these values into a new list variable called rowValue in the order that we defined when we created InsertCursor. That is, the latitude and longitude pair should be placed first, followed by the confidence value. Finally, we call the insertRow() function on the InsertCursor object assigned to the variable cur, passing in the new rowValue variable. We close by printing a message that indicates the progress of the script and also creating our except and finally blocks to handle errors and close the text file. Placing the file.close() method in the finally block ensures that it will execute, and close the file, even if there is an error in the previous try statement.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.151.252