Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't python allow me to delete files?

Tags:

python

file-io

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

like image 797
srmark Avatar asked Nov 28 '22 01:11

srmark


1 Answers

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
like image 86
Jon-Eric Avatar answered Dec 10 '22 01:12

Jon-Eric