![]() |
VOOZH | about |
os.walk() in Python is used to traverse directories recursively, allowing you to access all files and subdirectories in a directory tree. It is particularly useful when you need to perform operations on files spread across multiple folders.
Example: This code demonstrates how to traverse the current directory and print all directories and files.
Current directory: . Subdirectories: [] Files: ['Solution.py', 'input.txt', 'output.txt', 'driver'] ----------------
Explanation:
os.walk(top, topdown=True, onerror=None, followlinks=False)
Parameters:
Example 1: This program finds all .txt files in the directory tree.
Text files: ['input.txt', 'output.txt']
Explanation: f.endswith('.txt') filters files ending with .txt using files.
Example 2: This code counts the total number of files recursively in the given directory.
Total files: 4
Explanation:
Example 3: This program prints all directory paths in the directory tree.
Directories: ['.']
Explanation: