FileNotFound error when renaming files using shutil.move in Python

Question:

I’m in chapter 10 of Automate the Boring Stuff, and one of its activities suggests renaming files in order when one is missing (e.g., Spam001.txt, Spam002.txt, Spam004.txt, …).

When testing the code with a print() call and commenting out the shutil.move(), the program does what I want it to do.

I first ordered the files using lists and the sort function. The first list (order) contains the original filenames in order, and the second list (out) are the correct filenames.

Filenames are capitalsquiz1, capitalsquiz3, capitalsquiz4… It skips the capitalsquiz2, so I expect capitals3 to be renamed.

def fill_gap(folder):
    print(f'in {folder}')
    #create regex to find numbered filenames
    num = re.compile(r'^(.*?)((d)?(d)?(d))')
    
    order =[]
    out = []
    #go through all the files in the folder
    for oldfile in os.listdir(folder):
        
            
        mo = num.search(oldfile)
            
        if mo == None:
                continue
            
        order.append(mo.group(2))
        
    order.sort(key = int)
       
    for i in range(len(order)):

        order[i] = mo.group(1) + order[i]
        out.append(mo.group(1)+str(i+1))
        
    print(order)
    print(out)
    
    for i in range(len(order)):
        
        
        main = os.path.abspath(folder)
        old = os.path.join(main,order[i])
        
        order[i] = out[i]

        new = os.path.join(main, order[i])
        
        print(os.path.basename(old))
        print(os.path.basename(new))
        print (f'renaming "{old}" to "{new}"...')
        #shutil.move(old, new) 
                
                
            
        
fill_gap(r'C:\UsersAndreipyjectrand_quiz')

I’ve run it without the shutil.move and using print to check. It runs the way I want it to but when I add the shutil.move, it gives me the error:

Traceback (most recent call last):
  File "C:Program FilesPython311Libshutil.py", line 825, in move
    os.rename(src, real_dst)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\Users\Andrei\pyject\rand_quiz\capitalsquiz1' -> 'C:\Users\Andrei\pyject\rand_quiz\capitalsquiz1'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:UsersAndreipyjectfill_gap_in_name.py", line 53, in <module>
    fill_gap(r'C:\UsersAndreipyjectrand_quiz')
  File "C:UsersAndreipyjectfill_gap_in_name.py", line 48, in fill_gap
    shutil.move(old, new)
  File "C:Program FilesPython311Libshutil.py", line 845, in move
    copy_function(src, real_dst)
  File "C:Program FilesPython311Libshutil.py", line 436, in copy2
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "C:Program FilesPython311Libshutil.py", line 256, in copyfile
    with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\Andrei\pyject\rand_quiz\capitalsquiz1'
Asked By: Donj

||

Answers:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\Andrei\pyject\rand_quiz\capitalsquiz1'

You have to take this message seriously. No such file or directory. Period.

Now, where is the error?

Here:

order.append(mo.group(2))

You didn’t append the file name, but only the matched part of it.
Replace that command with

order.append(oldfile) 

(FYI, I then tested your such a fixed code and I don’t get that error message anymore.)


Yes, then you will get other error(s), but I don’t want to spoil the fun from revealing and fixing them by yourself. 😉

Answered By: MarianD
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.