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
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With