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

srm*_*ark 4 python file-io

我创建了一个python脚本,它从文本文件中获取文件列表,如果它们为空则删除它们.它正确检测空文件,但不想删除它们.它给了我:

(32, 'The process cannot access the file because it is being used by another process')
Run Code Online (Sandbox Code Playgroud)

我使用了两种不同的工具来检查文件是否被锁定,我确信它们不是.我使用了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")
Run Code Online (Sandbox Code Playgroud)

我尝试过使用os.unlink和os.remove.我在Vista64上运行Python 2.6

谢谢

Jon*_*ric 15

.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
Run Code Online (Sandbox Code Playgroud)


Ant*_*sma 9

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

此外,无需读取整个文件,您可以使用os.path.getsize(filename)== 0.


Ric*_*dle 6

这是打开文件的 - 你需要在尝试删除它之前关闭它:

ActiveFile = open(line);
Length = len(ActiveFile.read())
ActiveFile.close()   # Insert this line!
Run Code Online (Sandbox Code Playgroud)

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

Length = os.path.getsize(line)
Run Code Online (Sandbox Code Playgroud)