5

I have approximately 1500 raster files following this format:

m_3609922_nw_14_1_20100425 

I need these subsetted to, for example: 3609922nw. What are appropriate methods to rename large numbers of spatial data, that may or may not contain ancillary files (e.g. .xml, .ovr)?

1
  • 1
    Does it have to be ArcPy? If the filenames are that uniform, it is easy to create a batch file that does what you want using a combination of Excel and a text editor. Otherwise, with moderate difficulty (no more that ArcPy) you could write a batch file that uses regex to rename the files.
    – user3461
    Jun 13, 2012 at 19:31

1 Answer 1

12

Something like this ought to get you going...

import os
import arcpy
from arcpy import env

# directory containing rasters to be renamed
RASTER_DIR = 'C:/MyRasters/'

env.workspace = RASTER_DIR
for raster in arcpy.ListRasters():

    # get the raster name and file extension
    fileName,fileExtension = os.path.splitext(raster)

    # do some shenanigans to rename the file
    # based on your sample raster name, fileNameParts would look like
    # fileNameParts[0] = m
    # fileNameParts[1] = 3609922
    # fileNameParts[2] = nw
    # fileNameParts[3] = 14
    # fileNameParts[4] = 1
    # fileNameParts[5] = 20100425

    fileNameParts = fileName.split('_')
    compactFileName = fileNameParts[1] + fileNameParts[2] + fileExtension

    arcpy.Rename_management(raster,compactFileName)
2
  • How can I shorten the filename, but keep the underscores? e.g. instead of m_3609922_nw_14_1_20100425 , I would like to remove the "m_" to return 3609922_nw_14_1_20100425. Basically, I would like to remove the first 'x' number of characters from a filename.
    – derelict
    Aug 10, 2017 at 20:18
  • hmm I added + "_" + between each file part, there must be a more efficient method..
    – derelict
    Aug 10, 2017 at 20:54

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