Essay -Python recursively batch renaming files

Replace the key in the file name with the corresponding value by recursively replacing the specified path with the dict key pair.

import os
def test(path, dict) :
    """ recursively replaces the specified path with a dict key-value pair, replacing the keys in the file name with the corresponding values. "" "
    if os.path.isdir(path):
        for child in os.listdir(path):
            for k, v in dict.items():
                if child.find(k) > 0:
                    old = path + child
                    child = child.replace(k, v)
                    new = path + child
                    print(old, new)
                    os.renames(old, new)
            if os.path.isdir(path + child):
                child_path = path + child + '/'
                test(child_path, dict)


if __name__ == "__main__":
    path = './test_dataset/'
    ch_to_en_dict = {
        'red': 'red'.'orange': 'orange'.'yellow': 'yellow'.'green': 'green'.'green': 'cyan'.'blue': 'blue'.'purple': 'purple'
    }
    test(path, ch_to_en_dict)
Copy the code

For a directory hierarchy is relatively deep, the use of recursion to batch name is a good way!