Browse files and subfolders in python

When working with files and folders in Python, there are several ways to browse through them. In this article, we will explore three different approaches to solve the problem of browsing files and subfolders in Python.

Option 1: Using os.walk()

The os.walk() function is a powerful tool for traversing directories and retrieving all files and subfolders within a given directory. It returns a generator object that yields a tuple containing the current directory path, a list of subdirectories, and a list of filenames in that directory.

import os

def browse_files(directory):
    for root, dirs, files in os.walk(directory):
        for file in files:
            print(os.path.join(root, file))

In the above code, we define a function browse_files() that takes a directory path as input. We then use the os.walk() function to iterate over all the files in the directory and its subfolders. The os.path.join() function is used to concatenate the root directory path with the filename, providing the complete file path.

Option 2: Using glob.glob()

The glob module provides a convenient way to search for files using wildcard patterns. The glob.glob() function returns a list of paths matching the specified pattern.

import glob

def browse_files(directory):
    file_pattern = os.path.join(directory, '**', '*')
    files = glob.glob(file_pattern, recursive=True)
    for file in files:

In this code snippet, we first construct a file pattern using the os.path.join() function. The pattern consists of the directory path, followed by ‘**’ to indicate any number of subdirectories, and ‘*’ to match any filename. We then use glob.glob() with the recursive parameter set to True to search for all files matching the pattern.

Option 3: Using pathlib.Path()

The pathlib module provides an object-oriented approach to working with files and directories. The pathlib.Path() class represents a file or directory path, and provides various methods for navigating and manipulating paths.

from pathlib import Path

def browse_files(directory):
    path = Path(directory)
    for file in path.glob('**/*'):

In this code snippet, we create a Path() object with the specified directory path. We then use the glob() method of the Path object to search for all files and subfolders recursively. The resulting Path objects are printed to the console.

After exploring these three options, it is clear that the option 3: Using pathlib.Path() is the most elegant and Pythonic solution. It provides a high-level, object-oriented interface for working with files and directories, making the code more readable and maintainable. Additionally, the Path class offers a wide range of methods for path manipulation, making it a versatile choice for file and folder operations.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents