Search code examples
pythonfiledirectorybatch-renamerenaming

Renaming / Restructuring the layout of file names in a directory


import os

input_path = raw_input('Input file path here : ')

os.chdir(input_path)


for f in os.listdir(input_path):
    print f

I have "UDIM" texture files which are enumerated as such

1001_Base_Color.png, 1002_Base_Color.png, 1003_Base_Color.png.

My goal is to run through each file in the directory and reposition the number at the end of the file. name ---> Base_Color_1001.png

Any insight is appreciated !

Thank you


Solution

  • You can split each file name by underscores and then re-join them with underscores after appending the number to the end of the tokens:

    for f in os.listdir(input_path):
        name, ext = os.path.splitext(f)
        os.rename(f, ''.join(name.partition('_')[::-1]) + ext)