HOW TO

Append a new row into a feature attribute table from an existing CSV file using Python in ArcGIS Pro

Last Published: March 3, 2023

Summary

In ArcGIS Pro, ArcGIS API for Python can be used to automate the process of updating the field data records in the attribute table of a feature class from a CSV file. Follow the workflow described in this article to update the attribute table from a CSV file and add new rows using a stand-alone Python file (.py). The Python file also runs in Jupyter Notebook.

Procedure

  1. Import the necessary module.
import arcpy
  1. Specify the parameters for the feature class file location, the csv file location, and the fields involved.
fc = r"<featureClassPath>"
csv = r"<csvPath>"
copy_fields = ["<fieldName1>", "<fieldName2>", "<fieldName3>"]
  1. Create a dictionary to store the values for the fields.
csv_dict = {row[0]: row for row in arcpy.da.SearchCursor(csv, copy_fields)}
  1. Iterate through the features using the UpdateCursor() function.
with arcpy.da.UpdateCursor(fc, copy_fields) as cursor:
    for row in cursor:
        key = row[0]
        try:
            new_row = csv_dict[key]
        except KeyError:
            print(f"Entry not found in csv: {copy_fields[0]} = {key}")
            continue
        cursor.updateRow(new_row)
        del csv_dict[key]
  1. Apply the InsertCursor() function to insert any new fields in the feature class.
with arcpy.da.InsertCursor(fc, copy_fields) as cursor:
    for new_row in csv_dict.values():
        cursor.insertRow(new_row)
  1. Apply the print() function to show a message when the attribute table is updated.
print("<message>")

The code block below demonstrates the full working script.

fc = r"C:\Users\testUser\Documents\Article work\Article 29321\MyProject 29321\MyProject 29321.gdb\Schools_all"
csv = r"C:\Users\testUser\Documents\Article work\Article 29321\schoolLvl.csv"
copy_fields = ["NAME", "LEVEL_NO", "LEVEL"]

import arcpy
csv_dict = {row[0]: row for row in arcpy.da.SearchCursor(csv, copy_fields)}

with arcpy.da.UpdateCursor(fc, copy_fields) as cursor:
    for row in cursor:
        key = row[0]
        try:
            new_row = csv_dict[key]
        except KeyError:
            print(f"Entry not found in csv: {copy_fields[0]} = {key}")
            continue
        cursor.updateRow(new_row)
        del csv_dict[key]

with arcpy.da.InsertCursor(fc, copy_fields) as cursor:
    for new_row in csv_dict.values():
        cursor.insertRow(new_row)

print("Complete")

Article ID: 000029321

Software:
  • ArcGIS API for Python 1 x
  • ArcGIS Pro 3 0
  • ArcGIS Pro 2 8 x
  • ArcGIS Pro 2 x

Receive notifications and find solutions for new or common issues

Get summarized answers and video solutions from our new AI chatbot.

Download the Esri Support App

Related Information

Discover more on this topic

Get help from ArcGIS experts

Contact technical support

Download the Esri Support App

Go to download options