Select to view content in your preferred language

Batch Calculate Field with ArcPy

215
4
Jump to solution
06-05-2024 09:21 AM
LoreleiPalmquist
New Contributor II

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')

0 Kudos
1 Solution

Accepted Solutions
AlfredBaldenweck
MVP Regular Contributor

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

View solution in original post

4 Replies
AlfredBaldenweck
MVP Regular Contributor

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

LoreleiPalmquist
New Contributor II

Right. 😅 Thank you so much!!!

0 Kudos
AlfredBaldenweck
MVP Regular Contributor

Of course. Also, sorry I wrote that in a hurry and it came out terser than I meant.

0 Kudos
LoreleiPalmquist
New Contributor II

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.

0 Kudos