I’ve created a file called program1.py in my /home/n00b directory.
I then opened python and I wanted to see if I could write a script to find it’s location. I did this:
for f in os.walk('/home/n00b'):
print 'searching', f
if 'program1.py' in f:
print 'found'
break
Why isn’t this working? It seems to be searching each file because my screen fills up with the ‘searching’, part, but it never finds it.
It isn’t working because
os.walkreturns a 3-tuple: current directory, list of directory names here, and list of filenames here:Your print statement should have shown you that. The
inoperator won’t look deeply into the tuple, and since your filename was not one of the three elements in the tuple at any point, your code didn’t find it.