I have a geodatabase including (cnty06,cnty07,cnty08,cnty09...) that I'd like to rename to (c06,c07,c08,c09...). I can use the ModelBuilder (or script from ModelBuilder) to complete this task. Is there a way to use Python to complete the same task?
-
This is a good beginner's question, but if you want to learn quickly and get even more out of Python and arcpy check out some of the links in this question: What are some resources for learning ArcPy?– blah238May 5, 2014 at 18:35
-
1I know this isn't what you asked, but from the perspective of a software developer, I would definitely not appreciate such a change. I can read "cnty06" and have a good idea that I'm probably looking at some kind of county specific information. "c06" is meaningless to me. There's only 2 hard problems in programming.– jpmc26May 6, 2014 at 0:32
-
I can totally understand what you're saying and fundamentally agree with you... but this is about how and not why. For those trying to break into python there are good help documents in your local install; tip: the python way usually has the same name as the tool used in model builder (look up rename.. find rename_management) and if you're really stumped export the model to python and you'll see what it's called, look it up in the doc and most of the time there's an example.– Michael StimsonMay 6, 2014 at 2:43
-
Thank you Michael for your help. I was able to export python and saw how it was done.– mershJul 24, 2014 at 14:54
1 Answer
If they are all have the same name schema then you should be able to do the following:
import arcpy
arcpy.env.workspace = 'LOCATION OF THE GDB'
fcs = arcpy.ListFeatureClasses("*cnty*","")
for fc in fcs:
arcpy.Rename_management(fc, "%s%s" % (fc[0:1],fc[-2:]))
-
3The Python docs, recommended using str.format(var) over %s. "This method of string formatting is the new standard in Python 3, and should be preferred to the % formatting described in String Formatting Operations in new code." Therefore, more compatible (long-term) code would be
arcpy.Rename_management(fc, "{0}{1}".format( fc[0:1], fc[-2:]) )
. May 5, 2014 at 19:01 -
1
-
2I would prefer the
replace
method, personally:fc.replace('cnty', 'c')
. Much clearer and simpler. Also, does the pattern still work without the leading*
? If so, leaving it off might help avoid accidentally renaming the feature classes you don't intend to:"cnty*"
.– jpmc26May 6, 2014 at 0:36 -
I'm with blah238 on this one, from a readability perspective I definitely prefer the % formatting. It's similar to the C printf and you can tell at a glance what the string is going to look like. May 6, 2014 at 2:37