3

I have a large directory containing image files and need to change one character within the name of each file name. The character is in the same place in each file name (17). I think I need to use the 'replace' string function but as I am very new to Python I am not sure how to write this in a script (I work in GIS and have just started learning Python). Any help would be greatly appreciated. The character I need to change is the '1' after Nepal_Landscape_S'in the file name Nepal_Landscape_S1_LayerStacked_IM9_T44RQR_stack4.tif I simply need to change this to 2, like: Nepal_Landscape_S2_LayerStacked_IM9_T44RQR_stack4.tif

J Clifford
  • 205
  • 2
  • 5
  • what's wrong with `s = 'Nepal_Landscape_S1_LayerStacked_IM9_T44RQR_stack4.tif'` `s = s.replace('1', '2')` – danidee May 05 '16 at 14:40

1 Answers1

2

You can use the string replace method as you suspect along with os.rename.

import os
files = os.listdir("path/to/files")
for src in files:
    dst = src.replace('S1', 'S2')
    os.rename(src, dst)

If you are able to use your shell for this type of task, there may be simpler solutions, like the rename bash command: rename S1 S2 *S1*

Micah Smith
  • 4,203
  • 22
  • 28