Reputation: 1135
In the directory structure:
"~/clients/images/"
where clients
contains almost 1000 images
subdirectories, I need to discover which of these subdirectories are missing the file master.jpg
. I've tried unsuccessfully to print the desired output to the console, and I have tried writing it to a .txt file.
import os
path = os.path.expanduser('~/clients/images/')
mast = '/master.jpg'
print '\nFinding missing masters...n'
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
recipe = os.path.join(dirpath, filename)
if "master.jpg" not in filenames:
print str(dirnames), '\n'
What this currently does is to seemingly print a ton of empty lists ("[]") and newlines, which is definitely not what I want (all I want to know is which subdirectories are missing 'master.jpg'.)
Upvotes: 0
Views: 30
Reputation: 5236
Try this:
for dirpath, dirnames, filenames in os.walk(path):
if "master.jpg" not in filenames: print dirpath
For each 3-element object generated by the os.walk
generator, the first element (dirpath
in your code) represents the directory being examined. The third element (filenames
in your code) is a list containing all files found in that directory, so checking for the absence of master.jpg
in filenames
is the right thing to do.
I'm assuming that master.jpg
will always be a file - if there is the possibility that there could be a subdirectory named master.jpg
(seems odd, but the requirements are yours and not mine), then you might have to do:
for dirpath, dirnames, filenames in os.walk(path):
if "master.jpg" not in filenames and "master.jpg" not in dirnames: print dirpath
Upvotes: 1