My goal is to iterate through several feature classes and rename each feature class based on a field value within the feature class's attribute table. These feature classes are a single polygon feature, thus they only have a single row in the attribute table. I was thinking I could use the Rename GP tool to do this so I've got that part figured out. Next I can use the SearchCursor to find the field value that I want to use to rename the feature class with.
So I'm struggling here in two places. First, I'm unsure how to iterate through each of the feature classes to get their current names and then apply that to the first parameter of the arcpy.Rename_management tool. I know I can get the name of the feature class using arcpy.Describe but I'm stuck after that. Second, I'm struggling with how to assign each of the field values from the attribute table to a variable to be used for the second parameter of the Rename tool. I can easily print the name using rows = arcpy.SearchCursor(fc, "", "", "name") for row in rows: print row.name
but I'm struggling with how to assign its value to a variable.
Let me know if I need to explain this any better.
Answer
You can try something like this:
import arcpy
import glob
def main():
for f in glob.glob(r'C:\test\*.shp'):
rows = arcpy.SearchCursor(f, '', '', 'name')
for r in rows:
try:
arcpy.Rename_management(f, r.name)
except:
print 'Error: Unable to rename ' + f + ' to ' + r.name
break
del rows
if __name__ == '__main__':
main()
No comments:
Post a Comment