Python: Iterate over a root level path and print all its sub-directories and files
11. Iterate Over Root Path
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
For more Practice: Solve these Related Problems:
- Write a Python program to iterate over the contents of a root-level path using os.listdir() and print all subdirectories and files.
- Write a Python script to traverse a root directory with os.walk() and display the first level of directories and files.
- Write a Python function that accepts a root path, lists all its subdirectories and files, and returns a dictionary with separate keys for directories and files.
- Write a Python program to iterate over a specified root directory and print each file and subdirectory along with its size.
Go to:
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.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.