jeudi 3 septembre 2020

Got FileExistsError after successfully renaming a file using OS module

So I am trying to rename all the files with "%" in their filename in every folder in "img". The code below works. It finds files with "%" in their name and renames them. However, after renaming them, the FileExistsError shows.

    import string, random, os
    
    length = 40
    combination = string.ascii_uppercase + string.ascii_lowercase + string.digits
    result_str = "".join(random.choice(combination) for i in range(length))
    
    for folder in os.listdir("./static/img/"):
        for folder_ in os.listdir(f"./static/img/{folder}"):
            for files_ in os.listdir(f"./static/img/{folder}/{folder_}"):
                if "%" in files_:
                    print(f"./static/img/{folder}/{folder_}/{files_}")
                    os.rename(f"./static/img/{folder}/{folder_}/{files_}", f"./static/img/{folder}/{folder_}/{result_str}.jpg")
                    print("Changed Filename")

I've tried os.remove before the rename like what was suggested in another post, but it removes the file before it can even be renamed.




Aucun commentaire:

Enregistrer un commentaire