Python Removing Letters from File Names

I am trying to create a function that removes the first letters from all file names in a directory using python. The number of characters it will remove will depends on the number passed when calling on the function. If the new name after the removal is a duplicate of an existing name, an exception will occur and it will add “ex” as part of the files' new name

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import os 

def main():
    i = 0
    for root, dirs, files in os.walk("C:\\Users\\User\\Desktop\\Tests"):
             for filename in files:
                for filename2 in files:
                    newname = filename.split(i)
                    filename2 = filename[i:]
                    if filename != filename2: 
                        #print(filename)
                        continue
                # if a repetitious filename found your code for rename it will come up
                dst ="ex" + str(i) + ".txt"
                src = filename 
                dst ='ex'+ dst
                os.rename(src, dst)

# Driver Code 
if __name__ == '__main__': 

    # Calling main() function 
    main() 

I cannot get the function to remove the letters from the filename when passing the number of letters to remove and then comparing it to the other filenames in the same directory.

Beginner to python. Having trouble and don't know what to do next.
Last edited on
I can't look into this right now, but because Python relies heavily on indentation, please edit your post and add [code] and [/code] around your code to format it. This will help us read your code.
Last edited on
Oops forgot the code box xD sorry about that
Topic archived. No new replies allowed.