0
0
PythonHow-ToBeginner · 3 min read

How to List Files in Directory in Python: Simple Guide

Use the os.listdir() function to get all entries in a directory, or os.scandir() for more detailed info. To list only files, filter the results using os.path.isfile() or use pathlib.Path.iterdir() for a modern approach.
📐

Syntax

The main ways to list files in a directory are:

  • os.listdir(path): Returns a list of all entries (files and folders) in the directory at path.
  • os.scandir(path): Returns an iterator of directory entries with file type info.
  • pathlib.Path(path).iterdir(): Returns an iterator of Path objects for each entry.

You can filter these results to get only files.

python
import os
from pathlib import Path

# Using os.listdir
files_and_dirs = os.listdir('your_directory')

# Using os.scandir
with os.scandir('your_directory') as entries:
    for entry in entries:
        print(entry.name, entry.is_file())

# Using pathlib
p = Path('your_directory')
for entry in p.iterdir():
    print(entry.name, entry.is_file())
💻

Example

This example lists only files in the current directory using os.listdir() and os.path.isfile().

python
import os

directory = '.'  # current directory
files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
print(files)
Output
["file1.txt", "script.py", "image.png"]
⚠️

Common Pitfalls

Common mistakes when listing files include:

  • Not joining the directory path with the filename before checking if it is a file, causing wrong results.
  • Using os.listdir() without filtering, which returns folders and files mixed.
  • Not handling exceptions if the directory does not exist.
python
import os

# Wrong: checking isfile on name only
files_wrong = [f for f in os.listdir('.') if os.path.isfile(f)]  # May fail

# Right: join path before checking
files_right = [f for f in os.listdir('.') if os.path.isfile(os.path.join('.', f))]
print(files_right)
Output
["file1.txt", "script.py", "image.png"]
📊

Quick Reference

Summary of functions to list files:

FunctionDescription
os.listdir(path)List all entries (files and folders) in directory
os.scandir(path)Iterator with file type info for entries
os.path.isfile(path)Check if a path is a file
pathlib.Path(path).iterdir()Iterator of Path objects for entries

Key Takeaways

Use os.listdir() to get all entries and filter with os.path.isfile() to list only files.
os.scandir() and pathlib.Path.iterdir() provide more efficient and modern ways to list files.
Always join directory path with filename before checking if it is a file.
Handle exceptions for missing or inaccessible directories.
Filtering is necessary because directory listings include folders and files.