【问题标题】:Why won't python allow me to delete files?为什么python不允许我删除文件?
【发布时间】:2009-06-05 05:18:55
【问题描述】:

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

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

我使用了两种不同的工具来检查文件是否被锁定,并且我确定它们没有被锁定。我使用了 sysinternals 进程浏览器和 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

谢谢

【问题讨论】:

    标签: python file-io


    【解决方案1】:

    您需要在尝试删除文件对象之前调用.close()。

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

    这(我认为)做同样的事情,但更干净一点(恕我直言):

    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】:

      在取消链接之前尝试 ActiveFile.close()。

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

      【讨论】:

        【解决方案3】:

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

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

        或者只获取文件大小而不打开文件:

        Length = os.path.getsize(line)
        

        【讨论】:

          【解决方案4】:

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

          【讨论】:

            【解决方案5】:

            您可能需要先关闭文件句柄ActiveFile,然后再尝试删除它。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2010-12-05
              • 2013-12-21
              • 2017-09-02
              • 2012-09-11
              • 2011-07-04
              • 2012-03-01
              • 2013-02-13
              • 1970-01-01
              相关资源
              最近更新 更多