-2

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)
Shaye
  • 179
  • 13
  • Hi @Ouroborus, Please see my update 14/01/2022 above. I've done something similar to what you said which is to skip renaming the file if it has the same name as the one in the list else rename it if the names are different. I know it is skipping where the file names are the same and where they are different i.e. by the printing of X. But still I get files: spam001.txt, spam002.txt, spam003.txt and spam009.txt remaining in the folder?? For example when spam004.txt != spam005.txt it prints X. But I don't get spam005.txt in my folder directory – Shaye Jan 14 '22 at 12:40

1 Answers1

0

I eventually found a workaround though it may be clunky. Since renaming each file to a name used by a previous file is potentially causing the issue. I have decided to append an 'x' to the front of the files which are renamed with the same name as a file already present as below:

shutil.move(os.path.join(spamFolder, filename), os.path.join(spamFolder, 'x'+FileList[Counter1]))

I then simply us the os.walk feature to lstrip off the 'x'

Shaye
  • 179
  • 13