简体   繁体   中英

Can't find file with os.walk()

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM