Search code examples
pythonpython-3.xrenamefile-rename

Is there a way I can batch rename files in a folder with user input?


Wish to have user input rename batch photo files but with the end suffix changing.

Every couple of months I get given the same job, rename hundreds of photos. It takes me hours if not days to do. I so far have the code asking for the type of test (that the photo is capturing), the number of the test, the depth the test was conducted from and to from user input.

but I have hit a snag, I want to be able to batch rename but different photos show different depths. So for example I want the photos to be names: BH01_0-5m then the next photo be named. BH01_5-10m

But I only know how to code it so everything gets named BH01_0-5m

This is the code that I have so far for user input:

borehole = raw_input("What type of geotechnical investigation?")
type(borehole)

number = raw_input("What number is this test?")
type(number)

frommetre = raw_input("From what depth (in metres)?")
type(frommetre)

tometre = raw_input("What is the bottom depth(in metres)?")
type(tometre)

name = (borehole+number+"_"+frommetre+"-"+tometre)
print(name)

I get the title I would want for the first photo file but if I have like 4 photos in each folder they at the moment would get renamed the same exact thing as the user input. I am hoping to make the suffix sequential in lots of 5 metres (0-5, 5-10, 10-15, 15-20, 20-25 etc...).


Solution

  • I'm making a few assumptions here:

    • the name of the folder is the name of the borehole
    • the filenames for each borehole may differ, but when sorted alpha-numerically, the first one will be the one closest to the surface
    • all sets need increments of 5 metres

    What you're looking to do, can be done in two nested loops:

    • for all folders:
    • for all files in each folder:
    • rename the file to match the folder name and some depth sequentially

    Here's an example:

    from pathlib import Path
    from shutil import move
    
    root_folder = 'c:\\temp'
    for folder in Path(root_folder).iterdir():
        if folder.is_dir():
            startDepth = 0
            step = 5
            for file in Path(folder).iterdir():
                if file.is_file():
                    new_name = f'{folder.name}_{str(startDepth).zfill(3)}-{str(startDepth + step).zfill(3)}{file.suffix}'
                    print(f'would rename {str(file)} to {str(file.parent / Path(new_name))}')
                    # move(str(file), str(file.parent / Path(new_name)))
                    startDepth += step
    

    Note that I've also added .zfill(3) to each depth, since I think you'll prefer names like BH01_000-005.jpg to BH01_0-5.jpg, since they will sort more nicely.

    Note that this script only prints what it would do, you can simply comment out the print statement and remove the comment symbol in front of the move statement and it will actually rename files.