Reputation: 25
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.
Upvotes: 2
Views: 3931
Reputation: 1278
You can just change f -> f[2] to get the 3rd element of the tuple returned by walk.
for f in os.walk('/home/n00b'):
print 'searching', f
if 'program1.py' in f[2]:
print 'found'
break
Upvotes: 0
Reputation: 27575
The function os.walk()
doesn't work the way you expect. Instead of giving a list of files, it gives a tuple (similar to a list) with Directory, Subdirectory and Files. So, you could use:
for d, s, f in os.walk('/home/n00b'):
print 'searching', d
if 'program1.py' in f:
print 'found'
break
Hope it helps.
Upvotes: 0
Reputation: 375494
It isn't working because os.walk
returns a 3-tuple: current directory, list of directory names here, and list of filenames here:
for curdir, dirs, files in os.walk('/home/n00b'):
print 'searching', files
if 'program1.py' in files:
print 'found'
break
Your print statement should have shown you that. The in
operator 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.
Upvotes: 5