Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.path.isfile does not work as expected

Tags:

python

I am trying to scan my harddrive for jpg and mp3 files.

I have written the following script which works if I pass it a directory with file in the root but does not return anything if I pass it the root directory.

I am new to Python so would love some help.

def findfiles(dirname,fileFilter):

    filesBySize = {}

    def filterfiles(f):
        ext = os.path.splitext(f)[1][1:]
        if ext in fileFilter:
            return True
        else:
            False

    for (path, dirs, fnames) in os.walk(dirname):
        if len(fileFilter)>0:
            fnames = filter(filterfiles,fnames)

        d = os.getcwd()
        os.chdir(dirname)      
        for f in fnames:
            if not os.path.isfile(f) :
                continue

            size = os.stat(f)[stat.ST_SIZE]
            if size < 100:
                continue
            if filesBySize.has_key(size):
                a = filesBySize[size]
            else:
                a = []
                filesBySize[size] = a
            a.append(os.path.join(dirname, f))
          #  print 'File Added: %s' %os.path.join(dirname,f)
            _filecount = _filecount + 1
        os.chdir(d)

    return filesBySize
like image 450
gmoorevt Avatar asked Jan 22 '12 05:01

gmoorevt


1 Answers

Ah yes.

You're calling os.path.isfile(f) where f is the filename within the path. You'll need to provide an absolute path. If, indeed, this call is necessary (it should always return True).

Try changing your for-loop to:

    qualified_filenames = (os.path.join(path, filename) for filename in fnames)
    for f in qualified_filenames:

And you should be set!

Also, the calls to os.chdir() are not needed.

And, as I suggested in the comments, filterfiles should look more like this:

def filterfiles(f):
    ext = os.path.splitext(f)[1][1:]
    return ext in fileFilter

(You missed a return).

like image 140
Johnsyweb Avatar answered Sep 20 '22 13:09

Johnsyweb