Search code examples
pythonwindowsfile-rename

Batch rename files in a certain directory (remove prefixes)


I have a folder on Windows with pictures from various messengers, each with their own format. Some prefix IMG_, some image-, and my own pictures don't use any prefix. I want to write a script that cuts these and other prefixes. Example:

before: IMG_20220130_002520_211 after: 20220130_002520_211

I feel like I am close to the solution, only for some reason the code below gets the FileNotFoundError:

import os
path = "d:/MyName/Pictures/test"
files = os.listdir(path)
for i, filename in enumerate(files):
    if filename.startswith("IMG_"):
        print(filename.removeprefix("IMG_"))
        os.rename(filename, filename.removeprefix("IMG_"))

The print command print(filename.removeprefix("IMG_")) does work just fine and returns exactly what I want. It is just the renaming part that will not work. What am I missing here?

PS: I have searched plenty of threads discussing this particular problem, but I could not get any of the suggestions running...

PPS: Once I get this snipped done, I will just add elif conditions for each subsequent prefix.


Solution

  • I would use pathlib for that:

    from pathlib import Path
    
    path = Path("d:/MyName/Pictures/test")
    
    for item in path.iterdir():
        if item.name.startswith("IMG_"):
            print(item.name.removeprefix("IMG_"))
            item.rename(item.with_name(item.name.removeprefix("IMG_")))