I'm trying to step through a workspace and calculate all the fields that end in "Dep" to equal all the fields with matching field names (within the same feature class) minus the "Dep". However, it doesn't seem to like the {} method of putting a variable inside a string--it keeps saying "Invalid field {field}". Here's the code so far:
import os
import arcpy
workspace = "G:/Layer/gdb/Layer.gdb"
features = []
# Walks through the workspace, appending every feature class's file
# location to the list "features."
walk = arcpy.da.Walk(workspace, datatype="FeatureClass")
for dirpath, dirnames, filenames in walk:
for filename in filenames:
features.append(os.path.join(dirpath, filename))
# Calculates fields ending in "Dep" that match other fields to those matching
# fields' contents.
for feature in features:
tempFields = arcpy.ListFields(feature)
for field in tempFields:
compare = field.name + "Dep"
for i in tempFields:
if i.name == compare:
arcpy.management.CalculateField(feature, i.name, "!{field}!", 'PYTHON3')
Solved! Go to Solution.
You need to actually make it a formatted string. Add an f before the quotes.
arcpy.management.CalculateField(feature, i.name, f"!{field}!", 'PYTHON3')
Also, please see here for posting code; it's easier to read if formatted: How to insert code in your post - Esri Community
You need to actually make it a formatted string. Add an f before the quotes.
arcpy.management.CalculateField(feature, i.name, f"!{field}!", 'PYTHON3')
Also, please see here for posting code; it's easier to read if formatted: How to insert code in your post - Esri Community
Right. 😅 Thank you so much!!!
Of course. Also, sorry I wrote that in a hurry and it came out terser than I meant.
No worries. I did the sweat emoji bc I'm a little embarrassed I forgot to make it a formatted string. I've forgotten most of what I've learned about programming (four years without doing any), and getting back into it feels like swimming upstream.