Python: 比较文件名删除部分字符后的文件名

Python: Compare file name after deleting some characters from the name

Python:

我试图在从名称中删除 n 个字符后比较目录中的文件名。如果文件名存在于 strip 之后,那么它将在名称的末尾添加一个数字。

我创建了一个重命名目录中所有文件名的代码,但由于在删除后存在相同的文件名,我在尝试进行比较然后重命名时遇到了麻烦。

import os 

def main(): 
    i = 0

    for filename in os.listdir("C:\Users\User\Desktop\Tests"): 

        try:
            dirName != filename
            print (filename)

        except dirName == filename:
            dst ="dup" + str(i) + ".txt"
            src = dirName 
            dst ='Test'+ dst

        # rename() function will 
        # rename all the files 
            os.rename(src, dst) 
            i += 1

# Driver Code 
if __name__ == '__main__': 

    # Calling main() function 
    main() 

我知道它可以直接重命名文件,但无法与文件名进行比较,如果是同名则重命名。 python 的新手!

def main():
    i = 0
    for root, dirs, files in os.walk("C:\Users\User\Desktop\Tests"):
             for filename in files:
                for filename2 in files :
                    if filename != filename2: # if your file name is not repetitious you will pass it and compare next one 
                        #print(filename)
                        continue
                # if a repetitious filename found your code for rename it will come up
                dst ="dup" + str(i) + ".txt"
                src = filename 
                dst ='Test'+ dst
                os.rename(src, dst)