简体   繁体   中英

PermissionError: when using os.remove and os.rename in a loop in python

My code is for a script that download files and uses os.remove and os.rename during the process. My simplified code is:

for x in CPF:  
        onlyfiles = [f for f in listdir(r"D:\XXX\download") if isfile(join(r"D:XXX\download", f))]
        if onlyfiles!=[]:                
            files = glob.glob(r"D:XXX\download\*")        
            for f in files:                                
                os.remove(f)
        print("Now folder is empty")
        
    # Here download the data. Details omitted to simplify 
    
    # Here move the new files to another folder
    ID_CPF="CPF_"+x+".csv"
    new_folder = r"D:XXX\final\\"
    new_name = new_folder + ID_CPF
    list_of_files = glob.glob(r'C:XXX\Downloads\*.csv') 
    old_name = max(list_of_files, key=os.path.getctime)
    os.rename(old_name, new_name)

But I get this error message on the os.remove line:

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

What is causing this problem and how do I fix it?

As the error says, probably you have the file opened somewhere at the time of deletion, hence your code is not able to access it.

Make sure any file present at the location "D:XXX\download\*" is not open or being used somewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM