Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: os.walk() with enumeration

Tags:

python

In Python, I want to go list all the directories in a root directory, and print out the directory number together with the directory. I then want to print out the files in that directory.

The code would be something like:

for subdir, dirs, files in os.walk(root_dir):
    print "Directory " + str(dir_num) + " = " subdir
    for (file_num, file) in enumrate(files):
        print "File " + str(file_num) + " = " file

But how do can I get a value for dir_num, i.e. the number of the directory in the root directory? I know how to do this to print the file number, using enumerate(), but I'm unsure as to how to apply this to os.walk()...

like image 644
Karnivaurus Avatar asked Mar 24 '16 23:03

Karnivaurus


People also ask

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

The Python os. 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 is OS Walk ()?

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). root : Prints out directories only from what you specified.

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.


1 Answers

You can still use enumerate():

for dirnum, (subdir, dirs, files) in enumerate(os.walk(root_dir)):

You need the parentheses around subdir, dirs, files because enumerate() will return only two items: the index and the tuple subdir, dirs, files.

like image 190
zondo Avatar answered Oct 11 '22 09:10

zondo