: I just want to make a simple script that can work with files. OS's walk() seems to be able to single out all the directories in the current working directory according to the docs...
: grr...but it doesn't return a tuple as it says, it only gives a `generator' object, one I called help on, but had no luck whatsoever
: I hope this gets answered, please help me, at least to single out all the directories in a directory.
What is it that you want returned? os.walk() returns a generator, and generators are special objects that only yield the next value of a sequence when you call their next() method. Think of it as iterating over a list where the items in the list only exist for that iteration.
Each call to the next() method of the os.walk generator reurns a tuple containing a directory, a list of subdirectories in that directory, and a list of files in that directory. It recurses through all subdirectories under the path you pass to os.walk(), unless you remove them from the subdirs list at runtime.
So here's how you use os.walk():
>>> import os
>>> root = 'C:\\'
>>> for dir, subdirs, files in os.walk(root):
... for f in files:
... print os.path.join(dir, f)
The reason for generators is so that you don't have to wait for an entire sequence to be created before using it, and you don't have to use up memory to hold the whole thing in the meantime. It's really very cool.
Let's say you want to find every python script on your drive and do something with the path. You can write your own generator to wrap os.walk and "filter" the results a bit:
for dir, subdirs, files in os.walk(top):
for f in files:
if f[-3:].lower() == '.py':
yield dir, f
root = 'K:\\src\\py'
for dir, py in walk_py(root):
print os.path.join(dir, py)
if __name__ == '__main__': main()
Any function containing a "yield" statement is compiled by python to return a generator object.
$ select * from users where clue > 0
no rows returned