Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-recursive os.walk()

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.

like image 964
Paulo Freitas Avatar asked Nov 07 '10 11:11

Paulo Freitas


People also ask

Is OS walk recursive?

Use os. walk() to recursively traverse a directory For each subdirectory in the directory tree, os.

What does OS Walk () do?

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

What is the difference between OS Listdir () and OS walk?

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.

What does OS walk return in Python?

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.


2 Answers

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.

like image 140
Alecz Avatar answered Sep 23 '22 20:09

Alecz


next(os.walk(...)) 
like image 27
Ignacio Vazquez-Abrams Avatar answered Sep 24 '22 20:09

Ignacio Vazquez-Abrams