Skip to content Skip to sidebar Skip to footer

Os.rename Per String In Dir Name And Fileextension (lookup Table)

I am having trouble calling keys and values from lookup table to rename files. The task: in CWD, find each dir that ends =camID (e.g, ...=d5), then find raw_file inside =camID, th

Solution 1:

kinda hacky, but here's what works on that setup:

import os

config = {
    'g7': {},
    'd5': {},
}
config['g7']['cam_name'] = 'Canon-G7'
config['g7']['raw_file'] = ('cr2', 'jpg', 'mp4')

config['d5']['cam_name'] = 'Nikon-D5'
config['d5']['raw_file'] = ('nef', 'jpg', 'avi')

root = "test"

for camID in config:
    for dir in next(os.walk(root))[1]:
        if dir.lower().endswith(camID):
            for path, dirs, files in os.walk(os.path.join(root, dir)):
                for f in files:
                    if any([f.lower().endswith(x) for x in config[camID]["raw_file"]]):
                        os.rename(os.path.join(path, f), 
                                  os.path.join(path, "%s_%s" % (config[camID]['cam_name'], f)))

Please note the usage of os.walk() to get directories only, and then using it again to recursively walking through the whole subdirectory.

As a result, I have this as a starting point:

# find test
test
test/.jpg
test/04_camdire012345
test/04_camdire012345/.avi
test/04_camdire012345/.jpg
test/04_camdire012345/.mp4
test/02_camdirxyz=g7
test/02_camdirxyz=g7/bbb
test/02_camdirxyz=g7/bbb/ddd
test/02_camdirxyz=g7/bbb/ddd/.mp4
test/02_camdirxyz=g7/bbb/ddd/.jpg
test/02_camdirxyz=g7/bbb/ddd/.cr2
test/01_camdirab=d5
test/01_camdirab=d5/aaa
test/01_camdirab=d5/aaa/.wav
test/01_camdirab=d5/aaa/.avi
test/01_camdirab=d5/aaa/.jpg
test/01_camdirab=d5/aaa/.nef

And after running the code:

# find test
test
test/.jpg
test/04_camdire012345
test/04_camdire012345/.avi
test/04_camdire012345/.jpg
test/04_camdire012345/.mp4
test/02_camdirxyz=g7
test/02_camdirxyz=g7/bbb
test/02_camdirxyz=g7/bbb/ddd
test/02_camdirxyz=g7/bbb/ddd/Canon-G7.cr2
test/02_camdirxyz=g7/bbb/ddd/Canon-G7.jpg
test/02_camdirxyz=g7/bbb/ddd/Canon-G7.mp4
test/01_camdirab=d5
test/01_camdirab=d5/aaa
test/01_camdirab=d5/aaa/Nikon-D5.nef
test/01_camdirab=d5/aaa/Nikon-D5.jpg
test/01_camdirab=d5/aaa/Nikon-D5.avi
test/01_camdirab=d5/aaa/.wav

Post a Comment for "Os.rename Per String In Dir Name And Fileextension (lookup Table)"