Search code examples
pythonpython-3.xdirectoryfile-rename

renaming all images in folders using the name of the folder


I have a lot of folders. in each folder, there is an image. I want to rename all of the images with the name of its folder.

For example: Folder "1" has an image "273.jpg" I want to change it into the "1.jpg" and save it in another directory.

This is what I have done so far:

import os
import pathlib

root = "Q:/1_Projekte/2980/"

for path, subdirs, files in os.walk(root):
    for name in files:
        print (pathlib.PurePath(path, name))
        os.rename(os.path.join(path, name), os.path.join(path, os.path.basename(path)))
        print(os.path.basename(path))

The problem is that it works just for the first folder, then it jumps out with the error:

this file is already available...

the tree of folders and the images are like this:

Q:/1_Projekte/2980/1/43425.jpg

Q:/1_Projekte/2980/2/43465.jpg

Q:/1_Projekte/2980/3/43483.jpg

Q:/1_Projekte/2980/4/43499.jpg

So there is just one file in each directory!


Solution

  • Probably you have some hidden files in those directories. Check it out. If those files are not jpg, you can use following code:

    for path, subdirs, files in os.walk(root):
        for name in files:
            extension = name.split(".")[-1].lower()
            if extension != "jpg":
                continue
            os.rename(os.path.join(path, name), os.path.join(path, os.path.basename(path) + "." + extension))
            print(os.path.basename(path))
    

    This code extracts the extension of the file and checks if it is equal to the jpg. If file extension is not jpg, so continue statement will run and next file will check. If file type is jpg, script renames it. Also this code adds original file extension to the new name. Previous code didn't handle that. I hope this helpe you.