为什么Python不允许我删除文件?
我写了一个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。
谢谢
5 个回答
6
是你打开了这个文件 - 你需要先把它关闭,然后才能删除它:
ActiveFile = open(line);
Length = len(ActiveFile.read())
ActiveFile.close() # Insert this line!
或者你可以在不打开文件的情况下直接获取文件大小:
Length = os.path.getsize(line)
9
在删除文件之前,先试着用 ActiveFile.close() 关闭文件。
另外,不需要把整个文件都读出来,你可以直接用 os.path.getsize(filename) == 0 来检查文件是否为空。
18
在你尝试删除文件之前,必须先对文件对象调用 .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