I try to rename files by the dictionary value according to the keywords(key) I have. The old name of the files is a long string containing the keywords(key) not exactly the same!! I want to find the key included in the file name and rename the file by the corresponding value. The value should be the new name for all files. The dictionary structure would look like the table below:
Dictionary name: nameKeyWords
Key (Keywords) | Value (Name) |
---|---|
abb | 1 |
ave | 2 |
asp | 3 |
Below is the code I wrote, and it does work. However, the code is very inefficient because I use three for loop to go through all the files, keywords
(keys) in the dictionary, and all the file_name
in file_names
. Is there any method that can make the code more efficient? Thanks!
for (dir_path, dir_names, file_names) in walk(dir_path):
for file_name in file_names:
for keyWords in nameKeyWords:
if keyWords in file_name:
old_name = os.path.join(dir_path,file_name)
new_name = os.path.join(dir_path,nameKeyWords.get(keyWords)+'.csv')
os.rename(old_name, new_name)
else:
print(file_name)