Search code examples
pythonrename

File Name Change in Python: loop over dictionary values


In a folder, I have a file called "şğçı" and want to change it to "sgci". I created two lists and combined them to create a dictionary. Using the os library, I want to loop over this dictionary to replace the Turkish characters in the file names with the English character alternatives.

import os

path = r"C:\Users\ALpeR\Desktop/test_files"

turkish_character = ["ğ", "ç", "ş", "ü", "ö", "ı"]

english_alternatives = ["g", "c", "s", "u", "o", "i"]

character_dictionary = dict(zip(turkish_character, english_alternatives))
    
for root, dirs, files in os.walk(path):
    for file in files:
        file = file.lower()
        for key, value in character_dictionary.values():
            os.rename(os.path.join(root, file), os.path.join(root, file.replace(f"{key}",f"{value}")))

I believe that the problem could be in the last two lines of my code.


Solution

  • The original filename needs to be saved for os.rename before the dict mapping.

    Replace your for loop by this :

    for root, dirs, files in os.walk(path):
        for file in files:
            new_file = file
            new_file = new_file.lower()
            for key, value in character_dictionary.items():
                new_file = new_file.replace(key, value)
            os.rename(os.path.join(root, file), os.path.join(root, new_file))