[GIS] Import CSV column into existing feature using arcpy

arcgis-desktoparcmaparcpypython

My goal is to take a CSV that contains 50 rows and one column and import the data into a feature class with over 3,000 rows using arcpy. I want to pick a random row from the CSV and then iterate through the rows in the featureclass.

I will need to use this workflow constantly, but am unsure of how to read the CSV into arcpy.

Best Answer

I would use random.choice() to make a random selection from the .csv file and insert that into your FC rows using an Update Cursor.

import arcpy, csv, random

# Read csv file with names
file = r'C:\path\to\your\file.csv'
reader = csv.reader(open(file, "rb"), delimiter = ",", skipinitialspace=True)
listofnames = [name for line in reader for name in line]

# Update rows with random name selection
fc = r'C:\path\to\your\fc'

with arcpy.da.UpdateCursor(fc, ["yourfield"]) as cursor:
    for row in cursor:
        rand = random.choice(listofnames)
        row[0] = rand
        cursor.updateRow(row)
Related Question