Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

python - os.path.isfile does not work as expected

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...