Why doesn't python allow me to delete files?

I created a python script that gets a list of files from a text file and deletes them if they are empty. It correctly detects empty files, but does not want to delete them. This gives me:

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

I used two different tools to check if the files are locked or not, and I'm sure it is not. I used sysinternals process explorer and LockHunter. Alternatively, I can simply manually delete the files myself. Obviously, I do not want to do this for everyone, since there are hundreds in different places.

script:

 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") 

I tried using both os.unlink and os.remove. I am running Python 2.6 on Vista64

thanks

+4
source share
5 answers

You must call .close() on the file object before attempting to delete it.

Edit: And indeed, you should not open the file at all. os.stat() will tell you the file size (and another 9 other values) without opening the file.

This (I think) does the same, but a little cleaner (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 
+15
source

Try ActiveFile.close () before disconnecting.

In addition, reading the entire file is optional; you can use os.path.getsize (filename) == 0.

+9
source

You are the one with the file open - you need to close it before trying to delete it:

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

or just get the file size without opening the file:

 Length = os.path.getsize(line) 
+6
source

Do you open each file and then try to delete it? If so, try closing it first.

+4
source

You probably need to close the handle of the ActiveFile file before trying to delete it.

+3
source

Source: https://habr.com/ru/post/1285774/


All Articles