w3resource

Python: Iterate over a root level path and print all its sub-directories and files

Python Operating System Services: Exercise-11 with Solution

Write a Python program to iterate over a root level path and print all its sub-directories and files, also loop over specified dirs and files.

Sample Solution:

Python Code :

import os
print('Iterate over a root level path:')
path = '/tmp/'
for root, dirs, files in os.walk(path):
 print(root)

Sample Output:

Iterate over a root level path:
/tmp/

Python Code :

import os
print('Loop over dirs and files:')
path = '/tmp/'
for root, dirs, files in os.walk(path):
       print(root)
       for _dir in dirs:
           print(_dir)
       for _file in files:
           print(_file)

Output:

Loop over dirs and files:
/tmp/
0001.png
0002.png
0003.png
0004.png
0005.png
0006.png
0007.png
0008.png
0009.png
0010.png
.....
0037.png
0038.png
0039.png
0040.png
0041.png
0042.png
0043.png
0044.png
123.npy
123.npz

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a python program to access environment variables and value of the environment variable.
Next: Write a Python program to test whether a given path exists or not. If the path exist find the filename and directory portion of the said path.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Python: Unpack a Tuple

>>> items = (0, 'b', 'one', 10,  11, 'zero')
>>> a, b, c, d, e, f = items
>>> print(f)
zero
>>> a, *b, c = items
>>> print(b)
['b', 'one', 10, 11]
>>> *_, a, b = items
>>> print(a)
11