Skip to main content
 首页 » 编程设计

python之OSError : [Errno 13] Permission denied while calling os. 删除()

2024年11月01日9me-sa

对于某个脚本(我使用的是 Froglogic 的 Squish),我需要将某些文件复制到特定目录,运行应用程序,然后在进程结束后删除这些文件。问题出现在最后一部分。当我尝试时(例如)

        try: 
            os.remove("C:/Program Files (x86)/madeUpDirectory/madeUpSubdirectory/filler/madeUpFile.dll") 
        except LookupError, err: 
            test.fail("ERROR: The file could not be deleted.", str(err)); 

我得到一个

 OSError: [Errno 13] Permission denied: 'C:/Program Files (x86)/madeUpDirectory/madeUpSubdirectory/plugins/madeUpFile.dll' 

错误信息。我的理解是,这个特定错误通常表示没有正确的权限来写入有问题的目标......但这似乎不协调,因为在同一个脚本的早些时候,我使用这段代码将文件复制到该目录中:

try: 
    length_of_directory = len(origin) + 1 # +1? 
    for dirname, dirnames, filenames in os.walk(origin): 
        for filename in filenames: 
            file_path = os.path.join(dirname, filename)# [length_of_directory:] # Combine path and filename. 
            file_path = file_path.replace('\\', '/') # Reformat path to use unix-style path separators. 
            dstdir =  os.path.join(dstroot, os.path.dirname(file_path)[length_of_directory:]) 
            dstdir = dstdir.replace('\\', '/') # Reformat path to use unix-style path separators. 
            print os.access(dstdir, os.W_OK) 
            if not os.path.isdir(dstdir): 
                os.makedirs(dstdir) # create all directories, raise an error if it already exists 
            dstdir = os.path.join(dstdir, filename) 
            dstdir = dstdir.replace('\\', '/') # Reformat path to use unix-style path separators. 
            if not os.path.isfile(dstdir): 
                shutil.copy2(file_path, dstdir) 
                if os.path.isfile(dstdir): 
                    test.log("%s placed." % dstdir) 
            else: 
                test.log("NOTE: The file %s was already in position." % dstdir) 
except LookupError, err: 
    test.fail("ERROR: Something went wrong copying", str(err)); 

因此,我认为可以肯定地说我拥有所需的权限 - 特别是因为在覆盖之前运行脚本时放置在完全相同位置的文件时我没有收到任何错误。

我读到此错误消息可能是由于文件被某个进程或其他进程保持打开状态而引起的,但我不确定这是怎么发生的;出现此错误时,本应使用这些文件的进程已结束。

我肯定遗漏了一些东西 - 但是什么?我应该如何开始诊断这个问题?

请您参考如下方法:

尝试禁用防病毒软件并确保使用该文件的所有进程都已完成。如果这不能解决它,请尝试在删除之前稍作延迟,以确保在尝试删除之前完成该过程。