IndexError: list index out of range PLEASE HELP

3519
2
06-19-2014 11:35 AM
GrantWest
New Contributor
Trying to execute the following script tool to rename all the rasters in a folder to a shorter, but still uniquely identifying, version of the names they already have.  I am getting "IndexError: list index out of range", "Failed to execute (Rename).  I can't figure out what I need to change for this to work.  Any help is appreciated, thanks. 



import os
import arcpy
from arcpy import env
RASTER_DIR = 'C:/GIS_Working/QQ/Temp_monthly_means_gridded/'
env.workspace = RASTER_DIR

rasters = arcpy.ListRasters()

for raster in rasters: 
    fileName, fileExtension = os.path.splitext(raster)
    fileNameParts = fileName.split('_')
    compactFileName = fileNameParts[1] + fileNameParts[4] + fileExtension
    arcpy.Rename_management(raster, compactFileName)
Tags (2)
0 Kudos
2 Replies
RichardFairhurst
MVP Honored Contributor
If the split creates less than 5 items in its list, the index out of range will occur.  Since you have altered files in the same directory they no longer follow the pattern, so you can only run the tool once when all the Rasters have the full name.  You should check for len(fileNameParts) = 5 before renaming the file.  The list indexes are 0 based, so the 5th list item = index 4.

import os
import arcpy
from arcpy import env
RASTER_DIR = 'C:/GIS_Working/QQ/Temp_monthly_means_gridded/'
env.workspace = RASTER_DIR

rasters = arcpy.ListRasters()

for raster in rasters:  
    fileName, fileExtension = os.path.splitext(raster)
    fileNameParts = fileName.split('_')
    if len(fileNameParts) >= 5:
        compactFileName = fileNameParts[1] + fileNameParts[4] + fileExtension
        arcpy.Rename_management(raster, compactFileName)
0 Kudos
GrantWest
New Contributor
Ok. I think I ruined it by running it once with my part numbers incorrect.  Then I changed them, but it had already incorrectly renamed one output file with just two parts, so that would cause this error.  Thanks.
0 Kudos