file management
directory listing
list files
command line
file organization

How do I list all files of a directory?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Listing all files in a directory sounds simple, but the best answer depends on whether you want only the current directory, a recursive walk, or file names filtered by type. The most common solutions are command-line tools such as find and language APIs such as Python's pathlib or os.scandir.

Command-Line Listing

If you just need a quick shell answer, use a standard file listing tool. For the current directory only:

bash
ls -1

That prints one entry per line, but it includes both files and directories. If you want only files recursively, find is usually the better tool:

bash
find . -type f

This starts at the current directory and prints every regular file below it. That is often the cleanest command-line answer because it avoids guessing which entries are directories and which are files.

If you want a different starting directory, replace . with the target path:

bash
find /var/log -type f

Using Python With pathlib

For application code, pathlib is a strong default because it is readable and cross-platform.

To list only direct child files:

python
1from pathlib import Path
2
3directory = Path(".")
4
5for path in directory.iterdir():
6    if path.is_file():
7        print(path.name)

iterdir() lists the immediate contents of the directory. It does not recurse into subdirectories.

If you want recursive listing, use rglob:

python
1from pathlib import Path
2
3directory = Path(".")
4
5for path in directory.rglob("*"):
6    if path.is_file():
7        print(path)

This is convenient when you need to search nested folders without writing recursion manually.

Using os.scandir for Efficiency

os.scandir is another good option, especially when performance matters. It yields directory entries that already know some metadata, so checking whether an entry is a file can be efficient.

python
1import os
2
3with os.scandir(".") as entries:
4    for entry in entries:
5        if entry.is_file():
6            print(entry.name)

This is a strong choice when you want a fast direct-directory scan and do not need the richer object API of pathlib.

Decide Whether You Need Recursion

Many bugs come from not being explicit about whether subdirectories should be included. These are different tasks:

  • list direct children only,
  • list all files recursively,
  • list files matching a pattern.

For example, if you only want Python files below a directory:

python
1from pathlib import Path
2
3for path in Path(".").rglob("*.py"):
4    if path.is_file():
5        print(path)

Choosing the right API is mostly about choosing the right traversal depth and filter.

Handle Errors Deliberately

In real applications, directories may contain unreadable locations, broken links, or race conditions where files disappear during traversal. For simple scripts, that may not matter. For production code, handle those cases explicitly instead of assuming the directory tree is stable.

Even a basic existence check can improve clarity:

python
1from pathlib import Path
2
3directory = Path("/tmp")
4
5if not directory.exists() or not directory.is_dir():
6    raise ValueError("Path is not a directory")
7
8for path in directory.iterdir():
9    if path.is_file():
10        print(path.name)

Common Pitfalls

  • Using ls when you actually need only files and not directories.
  • Forgetting to decide whether the listing should be recursive.
  • Building manual recursion when find or pathlib.rglob already solves the problem cleanly.
  • Assuming every path is readable and stable during traversal.
  • Printing only file names when the calling code actually needs full paths.

Summary

  • Use find on the command line when you need a quick recursive file listing.
  • Use pathlib in Python for clear and cross-platform directory traversal.
  • Use os.scandir when you want a simple and efficient direct scan.
  • Be explicit about whether you want recursive results or only immediate children.
  • Decide early whether the caller needs file names, full paths, or filtered file types.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.