Python Loop through Folders and Files in Directory

Last Updated : 14 Jan, 2026

Given a folder that contains multiple files, the task is to go through each file and read its content one by one. For Example:

Folder structure:
docs/
├── a.txt -> "Hello"
├── b.txt -> "Python"
└── c.txt -> "Files"

Output: a.txt Hello
b.txt Python
c.txt Files

Explanation: Python visits every file inside the docs folder, opens it, reads its text, and prints both the file name and its content.

Using os.scandir()

This method reads directory entries directly using os.scandir() and provides both file names and their full paths, which allows files to be opened without extra path handling.

Python
import os

p = r"C:\Users\Public\Documents"

for e in os.scandir(p):
    if e.is_file():
        with open(e.path, "r") as f:
            print("Content of", e.name, ":")
            print(f.read())

Output

ScandirOutput
Snapshor of the terminal

Explanation:

  • os.scandir() returns directory entries and e.is_file() selects only files.
  • e.path gives the full path used by open() and e.name prints the file name.

Using pathlib Module

This method uses pathlib module which treats folders and files as objects, allowing direct access to file names and contents in a clean way.

Python
from pathlib import Path

p = Path(r"C:\Users\Public\Documents")

for f in p.iterdir():
    if f.is_file():
        print("Content of", f.name, ":")
        print(f.read_text())

Output

Output2
Snapshor of the terminal

Explanation:

  • Path() creates a directory object and iterdir() loops through all items inside it.
  • f.is_file() filters only files and f.read_text() reads the file content.

Using os.walk()

os.walk() recursively iterates through a directory tree. It returns the current path, a list of subfolders, and a list of files, making it ideal for processing entire directory structures.

Python
import os

p = r"C:\Users\Public\Documents"

for root, dirs, files in os.walk(p):
    for n in files:
        fp = os.path.join(root, n)
        with open(fp, "r", errors="ignore") as f:
            print(n)
            print(f.read())

Output

Output3
Snapshor of the terminal

Explanation:

  • os.walk() moves through all folders.
  • files contains file names.
  • os.path.join() builds the full path used by open().

Using glob Module

glob module allows file searching using wildcard patterns. It is helpful when you want to filter files by extension or match specific filename patterns in a directory.

Python
import glob
import os

p = r"C:\Users\Public\Documents"

for fp in glob.glob(p + "\\*"):
    if os.path.isfile(fp):
        with open(fp, "r") as f:
            print(os.path.basename(fp))
            print(f.read())

Output

Output4
Snapshor of the terminal

Explanation:

  • glob.glob() finds all matching file paths.
  • os.path.isfile() ensures the path is a file and os.path.basename() extracts the file name.
Comment