'Renaming files in same directory with Python

I have the following code which renames txt files according to a list with 8 elements. I can successfully rename the files if I move them to a different directory first.

However, when I want to move the files to the same directory and rename by swapping out withGapsFolder with spamFolder I don't get the expected result. Instead I get 4 files named: spam001.txt, spam002.txt, spam003.txt and spam009.txt.

The elements in FileList are: ['spam001.txt', 'spam002.txt', 'spam003.txt', 'spam005.txt', 'spam006.txt', 'spam007.txt', 'spam008.txt', 'spam009.txt']

The text files in the directory are: ['spam001.txt', 'spam002.txt', 'spam003.txt', 'spam004.txt', 'spam005.txt', 'spam006.txt', 'spam007.txt', 'spam008.txt']

for folderName, subfolders, filenames in os.walk(spamFolder):
for filename in filenames:

    if Counter1 == 8:
        sys.exit()
        
    #print(filename)
    #print(FileList[Counter1])
    shutil.move(os.path.join(spamFolder, filename), os.path.join(withGapsFolder, FileList[Counter1]))

    Counter1 = Counter1 + 1

    print(Counter1)

What I want is to rename the txt files in the same folder by essentially looping through the list elements.

Thanks

-PS This is an exercise from Automating the Boring Stuff with Python and the task is to create a gap in the files in the directory in their number sequence

Update: 14/01/2022

for folderName, subfolders, filenames in os.walk(spamFolder):
    for filename in filenames:
 
        if Counter1 == 8:
            sys.exit()

        print(filename+FileList[Counter1])
              
        if filename == FileList[Counter1]:
            Counter1 = Counter1 + 1
        else:
            #print(filename)
            #print(FileList[Counter1])
            shutil.move(os.path.join(spamFolder, filename), os.path.join(spamFolder, FileList[Counter1]))
            Counter1 = Counter1 + 1
            print('X')

print(Counter1)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source