Can someone help me with shortening my raster names ?

1116
2
Jump to solution
11-06-2020 02:04 PM
hansaneefernando
New Contributor

I have around 500 rasters in a folder with their names ending as follows. 

 

20190512_160716_104b_3B_AnalyticMS_SR_clip

20190512_160717_104b_3B_AnalyticMS_SR_clip

I want to remove the "AnalyticMS_SR_clip" part from all 500 rasters and save them in a new folder. I am very new to python, please help me. 

Thanks in Advance. 

0 Kudos
1 Solution

Accepted Solutions
DavidPike
MVP Frequent Contributor

copy the rasters to the intended new folder, then:

Just be careful what folder you select..

import os

#input folder to search (assuming no subdirectories)
#e.g - r'D:\myFolder'
folder = r'put_the_path_to_folder_here'

#this string will be searched for in filepath then deleted
text_to_replace = "AnalyticMS_SR_clip"

for root, dirs, files in os.walk(folder):
    for filename in files:

        #replace text_to_replace in name with empty string
        new_name = filename.replace(text_to_replace,"")

        #get path of original, create new path for replacement
        original_filepath = os.path.join(root, filename)
        new_filepath = os.path.join(root, new_name)

        #actually rename it
        os.rename(original_filepath, new_filepath)

View solution in original post

0 Kudos
2 Replies
DavidPike
MVP Frequent Contributor

copy the rasters to the intended new folder, then:

Just be careful what folder you select..

import os

#input folder to search (assuming no subdirectories)
#e.g - r'D:\myFolder'
folder = r'put_the_path_to_folder_here'

#this string will be searched for in filepath then deleted
text_to_replace = "AnalyticMS_SR_clip"

for root, dirs, files in os.walk(folder):
    for filename in files:

        #replace text_to_replace in name with empty string
        new_name = filename.replace(text_to_replace,"")

        #get path of original, create new path for replacement
        original_filepath = os.path.join(root, filename)
        new_filepath = os.path.join(root, new_name)

        #actually rename it
        os.rename(original_filepath, new_filepath)
0 Kudos
hansaneefernando
New Contributor

Thank you so much. This worked perfectly. Thanks again. 

0 Kudos