简体   繁体   English

PermissionError:在 python 的循环中使用 os.remove 和 os.rename 时

[英]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.我的代码用于下载文件并在此过程中使用 os.remove 和 os.rename 的脚本。 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:但我在 os.remove 行收到此错误消息:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: PermissionError: [WinError 32] 该进程无法访问该文件,因为它正被另一个进程使用:

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.确保位于"D:XXX\download\*"位置的任何文件都未打开或未在某处使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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