pythonfile-renamefile-move

os.rename [WinError 32] The process cannot access the file because it is being used by another process


I am trying to move the files from the source folder to destination folder, however I am getting the error

PermissionError Traceback (most recent call last) Cell In[23], line 9 7 print("Moving {} to {}".format(os.path.join(sourcepath, f), os.path.join(destination, subpath , f))) 8 #os.makedirs(os.path.join(destination, subpath), exist_ok=True) ----> 9 os.rename(os.path.join(sourcepath, f), os.path.join(destination, subpath , f))

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process

Apparently the file is being used by os.rename but I am struggling to close the loop. The code is:

sourcepath='C:/source'
destination='C:/destination'

(_,_,fnames) = next(os.walk(sourcepath))
for f in fnames:
    subpath = '/'.join(f.split('erFile_')[:+1])
    print("Moving {} to {}".format(os.path.join(sourcepath, f), os.path.join(destination, subpath, f)))
    os.rename(os.path.join(sourcepath, f), os.path.join(destination, subpath , f))

Any help is appreciated.


Solution

  • In this case, you can use the shutil.move function, which is more robust for file operations and will handle open files for you. Here's an example:

    import os
    import shutil
    
    sourcepath = 'C:/source'
    destination = 'C:/destination'
    
    (_, _, fnames) = next(os.walk(sourcepath))
    
    for f in fnames:
        subpath = '/'.join(f.split('erFile_')[:+1])
        source_file = os.path.join(sourcepath, f)
        destination_file = os.path.join(destination, subpath, f)
        print("Moving {} to {}".format(source_file, destination_file))
        
        try:
            shutil.move(source_file, destination_file)
        except Exception as e:
            print(f"Error moving {source_file} to {destination_file}: {e}")