Using Python to split and rename file

415
5
Jump to solution
08-05-2020 08:45 AM
JamesWhite5
New Contributor III

Good afternoon,

I am trying to split a file name and shorten it.  They are .tif files.  The code I am using is:

import arcpy
from arcpy import env

env.workspace = "C:\GIS_Projects\VA_1Meter_DEMs\Working_Shapefiles"

in_data = arcpy.ListRasters()
print in_data
for raster in in_data:
part = raster.split("_")
print part
out_data = part[0] + "_" + part[1] + "_" + part[3] + ".tif"
arcpy.Rename_management(in_data, out_data)

I am receiving this error:

Traceback (most recent call last):
File "C:/GIS_Projects/Pyth_Code/RenameDem.py", line 12, in <module>
arcpy.Rename_management(in_data, out_data)
File "C:\Program Files (x86)\ArcGIS\Desktop10.7\ArcPy\arcpy\management.py", line 4524, in Rename
raise e
RuntimeError: Object: Error in executing tool

The code does print out the raster list in the directory, and also prints out the first raster in the list split, so I know that part is working.  I am stumped where it is supposed to execute the name change though.

0 Kudos
1 Solution

Accepted Solutions
JoshuaBixby
MVP Esteemed Contributor

I should have caught this earlier, you are passing the wrong object to Rename.  Your current code is passing a list of rasters, not a single raster.  The line should read:

arcpy.Rename_management(raster, out_data)

View solution in original post

0 Kudos
5 Replies
JoshuaBixby
MVP Esteemed Contributor

It appears the code is failing on the first raster in the loop.  Can you provide the name of that raster, so we can see how you are setting out_data.

0 Kudos
JamesWhite5
New Contributor III

USGS_1m_x27y430_VA_Fairfax_County_2018.tif is the name of the first raster.  All of the files folow the same format.

0 Kudos
JamesWhite5
New Contributor III

I did make a mistake in my code, but that isn't the issue. I put part[3] and changed it to part[2], so it should be parts 0, 1 and 2.  I printed out the out_data just now as well, and it prints out the file name I want it to be.  It is failing at the Rename.management part of the script for some reason.

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

I should have caught this earlier, you are passing the wrong object to Rename.  Your current code is passing a list of rasters, not a single raster.  The line should read:

arcpy.Rename_management(raster, out_data)

View solution in original post

0 Kudos
JamesWhite5
New Contributor III

Ahhh, yes, that works like it should!  Thank you so much for that.

0 Kudos