-6

i'm trying to erase all indexes (characters) except the last 4 ones and the files' extension in python. for example: a2b-0001.tif to 0001.tif a3tcd-0002.tif to 0002.tif as54d-0003.tif to 0003.tif

Lets say that folders "a", "b" and "c" which contains those tifs files are located in D:\photos

  • there many of those files in many folders in D:\photos

that's where i got so far:

import os

os.chdir('C:/photos')

for dirpath, dirnames, filenames in os.walk('C:/photos'):

os.rename (filenames, filenames[-8:])

why that' not working?

1 Answers1

0

So long as you have Python 3.4+, pathlib makes it extremely simple to do:

import pathlib

def rename_files(path):
    ## Iterate through children of the given path
    for child in path.iterdir():
        ## If the child is a file
        if child.is_file():
            ## .stem is the filename (minus the extension)
            ## .suffix is the extension
            name,ext = child.stem, child.suffix
            ## Rename file by taking only the last 4 digits of the name
            child.rename(name[-4:]+ext)

directory = pathlib.Path(r"C:\photos").resolve()
## Iterate through your initial folder
for child in directory.iterdir():
    ## If the child is a folder
    if child.is_dir():
        ## Rename all files within that folder
        rename_files(child)

Just note that because you're truncating file names, there may be collisions which may result in files being overwritten (i.e.- files named 12345.jpg and 22345.jpg will both be renamed to 2345.jpg, with the second overwriting the first).

Reid Ballard
  • 1,480
  • 14
  • 19