I have many folders with shapefiles in each of them. I want to use python to go through each folder, add a new field to all the shapefiles containing the folder name.
Any ideas?
I would tackle this challenge with Walk. Then loop through the feature classes and add the directory names using an UpdateCursor.
import arcpy, os
# The input (base) directory
workspace = r"C:\tmp"
# Generate an empty list, which will be populated with walk below
fcs = []
# Walk through all directories and directories and list all feature classes
walk = arcpy.da.Walk(workspace, datatype="FeatureClass")
for dirpath, dirnames, filenames in walk:
for filename in filenames:
fcs.append(os.path.join(dirpath, filename))
# Loop through the fcs list, add field and add the directory name
for fc in fcs:
arcpy.AddField_management(fc, field_name = "folder", field_type = "TEXT", field_length = 250)
dirname = os.path.dirname(fc)
with arcpy.da.UpdateCursor(fc, "folder") as cursor:
for row in cursor:
row[0] = dirname
cursor.updateRow(row)
dirname = os.path.dirname(fc)
with dirname = os.path.basename(os.path.dirname(fc))
.
fc_dict = {}
right underneath fcs = []
. While "walking", if filename in fc_dict.keys(): fc_dict[filename].append(os.path.join(dirpath, filename)) else fc_dict[filename] = [os.path.join(dirpath, filename)]
. You'll create a dictionary where the key is the filename and the value is a list of all the corresponding files. At the very end of the script, iterate the dictionary and merge each value. dictionaries are one of the best things about python. docs.python.org/2/tutorial/datastructures.html#dictionaries
as just an outline of ideas: first you can get the folder name with something like:
os.path.relpath(".","..")
or also getting the path of directory and parsing it using 'split'
or you could try using os.walk
then find shapefiles with a matching string (again parsing names as needed) using arcpy.ListFeatureClasses()
you can iterate through
then pass that string to AddField_management:
arcpy.AddField_management (FC, fieldname, fieldtype)
then populate it with CalculateField
arcpy.CalculateField_management (fc, fieldname, data)