tags:

views:

547

answers:

5

I've created a python script that gets a list of files from a text file and deletes them if they're empty. It correctly detects empty files but it doesn't want to delete them. It gives me:

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

I've used two different tools to check whether the files are locked or not and I'm certain that they are not. I used sysinternals process explorer and LockHunter. Furthermore, I'm able to just manually delete the files myself. I obviously don't want to do that for all of them as there are hundreds in various locations.

The 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've tried using both os.unlink and os.remove. I'm running Python 2.6 on Vista64

Thanks

+14  A: 

You need to call .close() on the file object before you try and delete it.

Edit: And really you shouldn't be opening the file at all. os.stat() will tell you the size of a file (and 9 other values) without ever opening the file.

This (I think) does the same thing but is 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
Jon-Eric
Aha, I'm an idiot.
Mr Grieves
+4  A: 

Are you opening each file and then trying to delete it? If so, try closing it first.

jdigital
+3  A: 

You probably need to close the filehandle ActiveFile before you try to delete it.

David Zaslavsky
+6  A: 

It's you that has 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 filesize without opening the file:

Length = os.path.getsize(line)
RichieHindle
+7  A: 

Try ActiveFile.close() before doing the unlink.

Also, reading the whole file isn't necessary, you can use os.path.getsize(filename) == 0.

Ants Aasma