I'm looking for a way to do a non-recursive os.walk()
walk, just like os.listdir()
works. But I need to return in the same way the os.walk()
returns. Any idea?
Thank you in advance.
Use os. walk() to recursively traverse a directory For each subdirectory in the directory tree, os.
OS. walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).
listdir() method returns a list of every file and folder in a directory. os. walk() function returns a list of every file in an entire file tree.
os. walk() returns a list of three items. It contains the name of the root directory, a list of the names of the subdirectories, and a list of the filenames in the current directory.
Add a break
after the filenames for loop:
for root, dirs, filenames in os.walk(workdir): for fileName in filenames: print (fileName) break #prevent descending into subfolders
This works because (by default) os.walk
first lists the files in the requested folder and then goes into subfolders.
next(os.walk(...))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With