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.
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: