简体   繁体   English

Python:从文件名中删除一些字符后,比较文件名

[英]Python: Compare file name after deleting some characters from the name

Python: 蟒蛇:

I'm trying to compare file names in a directory after stripping some n characters from the name. 从名称中删除一些n个字符后,我试图比较目录中的文件名。 If the file name exists after the strip, then it will add a number to the end of the name. 如果文件名位于该条之后,则它将在名称末尾添加一个数字。

I created a code that renames all the file names in the directory, but I'm having trouble trying to do the comparison AND THEN renaming due to the existing same file name after the 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() 

I get it to rename the files directly but unable to do the comparison with the file names THEN renaming if it is the same name. 我得到它直接重命名文件,但是无法与文件名进行比较,如果名称相同则重命名。 New to python! 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM