Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading