afrologicinsect
afrologicinsect

Reputation: 171

Rename files in Multiple Folders with os

I have multiple folders with images, with the following folder structure, whose files I would like to rename.

Parent Dir

Folder 1

xyz.jpg abc.png ...

Folder 2

def.jpg xdd.png ...

rename.py

## rename.py
import os

## Function to rename
def main():
    folders = ["Folder_1", "Folder_2"]
    for folder_name in folders:
        for count, filename in enumerate(os.listdir(folder_name)):
            if folder_name == "Folder_1":
                dst = f"Folder_1 {str(count)}.jpg"
                src = f"{folder_name}/{filename}"
                dst = f"{folder_name}/{dst}"
            elif folder_name == "Folder_2":
                dst = f"Folder_2 {str(count)}.jpg"
                src = f"{folder_name}/{filename}"
                dst = f"{folder_name}/{dst}"

            os.rename(src, dst)

if __name__ == '__main__':
    main()

However two issues come up:

  1. how can I accommodate for 'png'?
  2. when code is run only folder 2 gets changed.

Noobing this through and would appreciate your help.

Upvotes: 0

Views: 426

Answers (1)

Rabinzel
Rabinzel

Reputation: 7913

You can use the functionality of os.path to extract the file extension and use it for renaming your file. I recreated your directories with .png and .jpg images, and running your code, both folder1 and folder2 worked. There must be a typo or something else causing the problem.

Here is the function you could use instead:

## rename.py
import os

def main():
    folders = ["folder1", "folder2"]
    for folder_name in folders:
        for count, filename in enumerate(os.listdir(folder_name)):
            _, ext = os.path.splitext(os.path.basename(filename))
            newfilename = f"{folder_name} {str(count)}{ext}"
            src = f"{folder_name}/{filename}"
            dst = f"{folder_name}/{newfilename}"
            os.rename(src, dst)

if __name__ == '__main__':
    main()

Upvotes: 1

Related Questions