代码之家  ›  专栏  ›  技术社区  ›  srmark

为什么python不允许我删除文件?

  •  4
  • srmark  · 技术社区  · 17 年前

    我创建了一个python脚本,它从一个文本文件中获取一个文件列表,并在文件为空时将其删除。它正确地检测到空文件,但不想删除它们。它给了我:

    (32, 'The process cannot access the file because it is being used by another process')
    

    我使用了两种不同的工具来检查文件是否被锁定,我确信它们不是。我使用了SysInternals Process Explorer和LockHunter。此外,我可以自己手动删除文件。我显然不想为他们所有人都这样做,因为在不同的地方有数百个。

    剧本:

    import os.path
    import sys
    
    def DeleteFilesFromListIfBlank(PathToListOfFiles):
        ListOfFiles = open(PathToListOfFiles)
        FilesToCheck = [];
        for line in ListOfFiles.readlines():
            if(len(line) > 1):
                line = line.rstrip();
                FilesToCheck.append(line)
        print "Found %s files to check.  Starting check." % len(FilesToCheck)
    
        FilesToRemove = [];
        for line in FilesToCheck:        
            #print "Opening %s" % line
            try:
                ActiveFile = open(line);
                Length = len(ActiveFile.read())
                if(Length < 691 and ActiveFile.read() == ""):
                    print "Deleting %s" % line
                    os.unlink(line);
                else:
                    print "Keeping %s" % line
            except IOError,message:
                print "Could not open file: $s" % message
            except Exception as inst:
                print inst.args
    
    DeleteFilesFromListIfBlank("C:\\ListOfResx.txt")
    

    我尝试同时使用os.unlink和os.remove。我在vista64上运行python 2.6

    谢谢

    5 回复  |  直到 17 年前
        1
  •  15
  •   Jon-Eric    17 年前

    你需要打电话 .close() 在尝试删除文件对象之前。

    编辑:实际上你根本不应该打开文件。 os.stat() 将告诉您文件的大小(以及9个其他值),而不必打开文件。

    这(我认为)也有同样的作用,但有点清洁(imho):

    import os
    
    _MAX_SIZE = 691
    
    def delete_if_blank(listFile):
        # Make a list of files to check.
        with open(listFile) as listFile:
            filesToCheck = filter(None, (line.rstrip() for line in listFile.readlines()))
    
        # listFile is automatically closed now because we're out of the 'with' statement.
    
        print "Found %u files to check. Starting check." % len(filesToCheck)
    
        # Remove each file.
        for filename in filesToCheck:
            if os.stat(filename).st_size < _MAX_SIZE:
                print "Deleting %s" % filename
                os.remove(filename)
            else:
                print "Keeping %s" % filename
    
        2
  •  9
  •   Ants Aasma    17 年前

    在取消链接之前,请尝试activefile.close()。

    另外,不需要读取整个文件,可以使用os.path.getsize(filename)==0。

        3
  •  6
  •   RichieHindle    17 年前

    它是 你 文件已打开-您需要先关闭它,然后再尝试删除它:

    ActiveFile = open(line);
    Length = len(ActiveFile.read())
    ActiveFile.close()   # Insert this line!
    

    或者在不打开文件的情况下获取文件大小:

    Length = os.path.getsize(line)
    
        4
  •  4
  •   jdigital    17 年前

    是否打开每个文件,然后尝试删除它?如果是,请尝试先关闭它。

        5
  •  3
  •   David Z    17 年前

    您可能需要关闭文件句柄 ActiveFile 在你尝试删除它之前。