0
0
PythonHow-ToBeginner · 3 min read

How to List Files Using pathlib in Python: Simple Guide

Use the Path class from the pathlib module and call its iterdir() method to list files and folders in a directory. You can filter only files by checking is_file() on each item.
📐

Syntax

The basic syntax to list files using pathlib involves creating a Path object for the directory and then using iterdir() to get all entries. You can then filter these entries to get only files.

  • Path('directory_path'): Creates a path object for the directory.
  • iterdir(): Returns an iterator of all files and folders inside the directory.
  • is_file(): Checks if the path is a file (not a folder).
python
from pathlib import Path

p = Path('your_directory')
for entry in p.iterdir():
    if entry.is_file():
        print(entry.name)
💻

Example

This example lists all files in the current directory and prints their names. It shows how to use Path, iterdir(), and is_file() together.

python
from pathlib import Path

# Create a Path object for the current directory
current_dir = Path('.')

# Iterate over all entries in the directory
for item in current_dir.iterdir():
    # Check if the entry is a file
    if item.is_file():
        print(item.name)
Output
example.py notes.txt image.png
⚠️

Common Pitfalls

One common mistake is to forget filtering only files, which results in folders being listed too. Another is using string paths instead of Path objects, which loses pathlib's benefits.

Also, using glob('*') instead of iterdir() can be confusing; glob supports patterns but iterdir() is simpler for all entries.

python
from pathlib import Path

p = Path('.')

# Wrong: prints files and folders
for entry in p.iterdir():
    print(entry.name)

print('---')

# Right: prints only files
for entry in p.iterdir():
    if entry.is_file():
        print(entry.name)
Output
example.py notes.txt my_folder --- example.py notes.txt
📊

Quick Reference

MethodDescription
Path('dir')Create a Path object for a directory
iterdir()Get all entries (files and folders) in the directory
is_file()Check if an entry is a file
nameGet the name of the file or folder
glob('*.ext')Get files matching a pattern (e.g., '*.txt')

Key Takeaways

Use pathlib.Path and its iterdir() method to list directory contents easily.
Filter entries with is_file() to list only files, excluding folders.
Path objects provide convenient methods like name and glob for file handling.
Avoid mixing string paths and Path objects to keep code clean and consistent.