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.
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It only takes a minute to sign up.Sign up to join this community
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 = dirname cursor.updateRow(row)
as just an outline of ideas: first you can get the folder name with something like:
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)