Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

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()
share|improve this answer
    
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 Sep 23 '11 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 –  Allan Adair Sep 25 '11 at 18:01
1  
@wilbev It also allows you to call the class from another class e.g. MyClass.main() –  Hairy Sep 26 '11 at 6:56
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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