Search code examples
pythonfile-rename

Rename images to the folder name with Python


I want to rename images that were previously copied from multiple subfolders to the name of the subfolder from which the image came. With my actual code I can only rename images, when I enter the actual file name. But this name always varies.

For example:

C:/sub/folder/1/

rename these images from this folder to 1.jpg

My actual code:

paths = (os.path.join(root, filename)
for root, _, filenames in os.walk(dir_dst):
    for filename in filenames:        
        for path in paths:
            newname= path.replace('image_name','new_image_name')
            if newname != path:
                os.rename(path, newname)

I hope you understand what I mean.


Solution

  • I've found the solution:

    import os, shutil
    
    src_g = os.getcwd()
    dst_g0 = src_g.split('\\')
    dst_g0.pop()
    dst_g = '\\'.join(dst_g0)+'\\DestinationFolder\\'
    
    for i in os.listdir(src_g):
        if os.path.isdir(i):
            name = i
            neuer_pfad = src_g+'\\'+name+'\\folder_with_images\\'
            for j in os.listdir(neuer_pfad):
                neue_datei = neuer_pfad+j
                if os.path.isfile(neue_datei):
                    shutil.copyfile(neue_datei, dst_g+name+'_'+j)