Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using os.walk() to recursively traverse directories in Python

Tags:

python

os.walk

I want to navigate from the root directory to all other directories within and print the same.

Here's my code:

#!/usr/bin/python

import os
import fnmatch

for root, dir, files in os.walk("."):
        print root
        print ""
        for items in fnmatch.filter(files, "*"):
                print "..." + items
        print ""

And here's my O/P:

.

...Python_Notes
...pypy.py
...pypy.py.save
...classdemo.py
....goutputstream-J9ZUXW
...latest.py
...pack.py
...classdemo.pyc
...Python_Notes~
...module-demo.py
...filetype.py

./packagedemo

...classdemo.py
...__init__.pyc
...__init__.py
...classdemo.pyc

Above, . and ./packagedemo are directories.

However, I need to print the O/P in the following manner:

A
---a.txt
---b.txt
---B
------c.out

Above, A and B are directories and the rest are files.

like image 394
Nitaai Avatar asked Oct 09 '22 19:10

Nitaai


People also ask

How do I walk a directory in Python?

To traverse the directory in Python, use the os. walk() function. The os. walk() function accepts four arguments and returns 3-tuple, including dirpath, dirnames, and filenames.

Is os Listdir recursive?

listdir(path='. ') It returns a list of all the files and sub directories in the given path. We need to call this recursively for sub directories to create a complete list of files in given directory tree i.e.

How does Python os walk work?

walk() work in python ? 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).

How do I get a list of files in a directory and subfolders in Python?

os. listdir('dir_path') : Return the list of files and directories present in a specified directory path. os. walk('dir_path') : Recursively get the list all files in directory and subdirectories.


1 Answers

This will give you the desired result

#!/usr/bin/python

import os

# traverse root directory, and list directories as dirs and files as files
for root, dirs, files in os.walk("."):
    path = root.split(os.sep)
    print((len(path) - 1) * '---', os.path.basename(root))
    for file in files:
        print(len(path) * '---', file)
like image 308
Ajay Avatar answered Oct 28 '22 15:10

Ajay