Search code examples
pythonpython-3.xfile-rename

Filerenaming loop not functioning


I'm having trouble understanding why my code doesn't work. I want to rename each file in a particular folder in an order like this: Foldername_1 Foldername_2 Foldername_3 etc...

The code I wrote should increase the 'num' variable by 1 every time it reloops the for loop.

path = os.getcwd()
filenames = os.listdir(path)

    for filename in filenames:
        num = 0
        num = num + 1
        name = "Foldername_{}".format(num)
        os.rename(filename, "{}".format(name))

However I'm getting this Error:

FileExistsError: [WinError 183] Cannot create a file when that file already exists: '90' -> 'Foldername_1'


Solution

  • You are setting num to 0 for each iteration. Move the num = 0 out of the loop:

    num = 0
    for filename in filenames:
        num = num + 1
        name = "Foldername_{}".format(num)
        os.rename(filename, "{}".format(name))
    

    You don't need to format the name variable again; "{}".format(name) produces the same string as what is already in name. And rather than manually increment a number, you could use the enumerate() function to produce the number for you:

    for num, filename in enumerate(filenames, 1):
        name = "Foldername_{}".format(num)
        os.rename(filename, name)
    

    Take into account that os.listdir() doesn't list names in alphabetical order; rather, you'll get an order that is based on the on-disk directory structure, which depends on the order files where created and the exact filesystem implementation. You may want to sort manually:

    for num, filename in enumerate(sorted(filenames), 1):