Search code examples
pythonstringfilerenamesubdirectory

How to rename the sub files in a folder with the name of the parent file plus some index using python


I have files in the parent directory as given:

parent_folder
 |-file1
    |-img1.jpg
    |-img2.jpg
    |-img3.jpg
 |-file2
    |-img1.jpg
    |-img2.jpg
    |-img3.jpg

I want to rename the .jpg files by adding the name of the parent folder to it in Python. How to go about it?

parent_folder
 |-file1
    |-file1_img1.jpg
    |-file1_img2.jpg
    |-file1_img3.jpg
 |-file2
    |-file2_img1.jpg
    |-file2_img2.jpg
    |-file2_img3.jpg

i tried the following code but its not working:

def naming():
    path='D:/parent_folder'
    for root, dirs, files in os.walk(path):
        print(files)
        for name in files:
            print(name)
            newname = files + name
            os.rename(join(root,name),join(root,newname))

Solution

  • Something like this in Python 3.4+ should work:

    from pathlib import Path
    
    parent_folder = Path('d:/parent_folder')
    
    for obj in parent_folder.glob('*'):
        if obj.is_dir():
            for jpg in obj.glob('*.jpg'):
                jpg.rename(jpg.parent / f'{jpg.parent.name}_{jpg.name}')
    

    If your Python interpreter doesn't support f-strings, use this alternative version:

    from pathlib import Path
    
    parent_folder = Path('d:/parent_folder')
    
    for obj in parent_folder.glob('*'):
        if obj.is_dir():
            for jpg in obj.glob('*.jpg'):
                jpg.rename(jpg.parent / '{0}_{1}'.format(jpg.parent.name, jpg.name))
    

    And here is a proof of concept:

    $ cat ren.py 
    from pathlib import Path
    
    parent_folder = Path('testdir')
    
    for obj in parent_folder.glob('*'):
        if obj.is_dir():
            for jpg in obj.glob('*.jpg'):
                jpg.rename(jpg.parent / f'{jpg.parent.name}_{jpg.name}')
    $ tree testdir
    testdir
    ├── dir1
    │   ├── file1.jpg
    │   └── file2.jpg
    └── dir2
        ├── file1.jpg
        └── file2.jpg
    
    2 directories, 4 files
    $ python3 ren.py 
    $ tree testdir
    testdir
    ├── dir1
    │   ├── dir1_file1.jpg
    │   └── dir1_file2.jpg
    └── dir2
        ├── dir2_file1.jpg
        └── dir2_file2.jpg
    
    2 directories, 4 files
    $ 
    

    I hope it helps.