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: Unknown Arguments Using *arguments

If your function can take in any number of arguments then add a * in front of the parameter name:

def myfunc(*arguments):
 for a in arguments:
   print a
myfunc(a)
myfunc(a,b)
myfunc(a,b,c)