How do I modify my syntax to properly read an csv file and write the contents to a shapefile using an update cursor ?
# Read csv file & write to shapefile via update cursor import csv,os updateCursor = arcpy.da.UpdateCursor(r'sample.shp', ["Name", "OrderCount","Time","Miles"]) with open(r'CsvToShape.csv','rb') as f: reader = csv.reader(f) for row in reader: route = row order = row time = row mile = row for row in updateCursor: row.setValue(route = Name) ## row= order ## row = time ## row = mile updateCursor.updateRow(row)
You are using the older style cursor, you should look into using What is the data access module?—Help | ArcGIS Desktop .
More importantly, if you want to convert a CSV into a shapefile it is best to have some spatial data. Where is yours or how is it stored in the CSV?
Thanks for the advice.
I did not realize cursors as gone thru the following iterations:
I actually want to read a separate excel csv file and write the data (UpdateCursor) to same named shapefile fields.
I suggest starting a new question and providing a bit more information in that new question. For example, what does your data structure look like? I assume the Yes/No column values are currently stored as Text?
You've got a variable name collision on 'row'. The DA cursor row object is just an array/list.
You should probably choose between caching the contents of the CSV in a dictionary and stepping through the UpdateCursor linearly, and using a new cursor with an index-covered WHERE clause for each CSV row. This decision will dictate the structure of your code.
Creating a dictionary form the csv is straight forward but I still have the issue of passing the values to the cursor.
import csv,os updateCursor = arcpy.da.UpdateCursor(r'sample.shp', ["Name", "OrderCount","Time","Miles"]) with open(r'test.csv') as csvfile: reader = csv.DictReader(csvfile, delimiter = ",") for row in reader: updateCursor.updateRow(row)
To do a full update there are 3 separate processes. Update records, which occurs as you iterate through the updateCursor records and find a key match in the csv dictionary. Delete records (optional), which occurs as you iterate through the updateCursor records and do not find a key match in the csv dictionary. Update and Delete can be done as you do a single pass on all of the updateCursor records. Finally, Insert records, which I usually approach by first creating a dictionary of the updateCursor records after every record has been updated and deleted. Then I iterate through the csv file or csv dictionary records and if it is not in the updateCursor record dictionary, I insert that records using an InsertCursor into the FC being updated.
If the FC you are updating is empty and all you are doing is adding records, you need to use an insertCursor, not an updateCursor.