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, as well as 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 Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/os/python-os-exercise-11.php