Renaming a shapefile in Python 2.7

644
10
09-09-2019 07:20 PM
BlytheSchembri1
New Contributor III

Hi guys

I have a python script (written in 2.7) with takes a shapefile, renames it and then imports it into a SDE geodatabase. The creators of the shapefile have recently changed the file name to have a full stop halfway through the name which now causes the script to crash. 

I have tried running the following section of python to rename the shapefile but it only renames the .shp file and no other files that are part of the shapefile:

arcpy.env.workspace = "C:\\Users\\blythe schembri\\Downloads"
datasets = arcpy.ListFeatureClasses()
for fc in datasets:
      CorrectName = fc.replace('dbo.vNT_','')
arcpy.Rename_management(fc, CorrectName[:-4])

How do I make it rename all the shapefile components?

Thanks

Blythe

0 Kudos
10 Replies
JoeBorgione
MVP Esteemed Contributor

You'd want to use python (not arcpy) to rename all the files. But... Since your moving the shape file why not just rename it as you move it to your egdb?  See Copy Features—Data Management toolbox | ArcGIS Desktop 

can't wait to retire....
JoshuaBixby
MVP Esteemed Contributor

Could you provide a sample or example of a new shape file name?

0 Kudos
BlytheSchembri1
New Contributor III

An example new name would be Fences.shp

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

What about an example of the original/old name with the full stop in it? 

0 Kudos
BlytheSchembri1
New Contributor III

An example is dbo.vNT_Fence.shp

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

If the naming convention is consistent, i.e., you always want everything after an underscore, does this work for you?

>>> name = r"dbo.vNT_Fence.shp"
>>> name.split("_")[1]
'Fence.shp'
>>> arcpy.Rename_management(name, name.split("_")[1])
>>>
BlytheSchembri1
New Contributor III

I've had a chance to try making this script work again. Thank you all for your help.

I think I'm going to go with the copy features option.

The code above only renames the .shp file and not the others. In theory do I need to use a wildcard instead of .shp?

Thanks

Blythe

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

The Rename tool only renames the *.shp file and not the associated files?

0 Kudos
BlytheSchembri1
New Contributor III

Yep! very weird.

I've even exported the python script from ArcMap and when I run it outside ArcGIS it only renames the *.shp file

0 Kudos