3

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.

1 Answer 1

4

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()
3
  • Allan, that worked great, thank you very much. I haven't used the glob module before and I'm not understanding that last if statement that sets up whether the main function runs or not. Any chance you can explain what that means? What is the significance of the double underscores around "name" and "main"? I don't understand where name and main syntax is coming from.
    – wilbev
    Commented Sep 23, 2011 at 19:59
  • 1
    @wilbev, it's a coding style. I'd like to defer you to this explanation: artima.com/weblogs/viewpost.jsp?thread=4829 and en.wikipedia.org/wiki/Main_function#Python Commented Sep 25, 2011 at 18:01
  • 1
    @wilbev It also allows you to call the class from another class e.g. MyClass.main()
    – Hairy
    Commented Sep 26, 2011 at 6:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.