Cover Image for Os.walk() in python
169 views

Os.walk() in python

The os.walk() is a Python function that generates the file names in a directory tree by walking either top-down or bottom-up through the directory tree. It’s a useful tool for traversing directories, especially when you need to perform operations on files or directories within a directory tree.

Here’s how to use os.walk():

Python
import os

# Specify the root directory to start walking from
root_directory = "/path/to/your/directory"

# Use os.walk() to traverse the directory tree
for root, directories, files in os.walk(root_directory):
    print(f"Current directory: {root}")

    # Print all subdirectories in the current directory
    for directory in directories:
        print(f"Subdirectory: {os.path.join(root, directory)}")

    # Print all files in the current directory
    for file in files:
        print(f"File: {os.path.join(root, file)}")

In this code:

  • os.walk() is called with the root_directory as its argument.
  • It returns a generator that yields a tuple for each directory in the directory tree. The tuple contains three elements:
  • root: The current directory being traversed.
  • directories: A list of subdirectories in the current directory.
  • files: A list of files in the current directory.
  • The code then iterates through the generator, printing information about the current directory, subdirectories, and files within each directory.

You can use os.walk() for various tasks, such as searching for specific files, performing operations on files, or gathering information about the contents of a directory tree.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS