List files in a directory with Python (os.listdir, pathlib)
List files in a directory with Python. Examples use os.listdir, pathlib, glob, and os.scandir. Store results in a list, filter by extension, and recurse.
How can I list all files in a directory using Python and store them in a list?
To list all files in a directory using Python, grab the built-in os module and use os.listdir(path)—it spits out a list of filenames right away, like files = os.listdir('.') for the current folder. For a more object-oriented vibe, pathlib shines: files = [p.name for p in Path('your_dir').iterdir()]. Both methods store everything in a handy list you can sort, filter, or loop over instantly.
Contents
- Using os.listdir to List Files
- Modern Way with pathlib
- Advanced Options: glob and os.scandir
- Filtering Files, Subdirs, and Edge Cases
- Full Working Examples
- Sources
- Conclusion
Using os.listdir to List Files
Ever needed a quick dump of everything in a folder? os.listdir is your go-to classic from Python’s standard library. Pass it a path string—empty for current dir, or something like '/home/user/docs'—and it returns a list of strings with all entries (files and subdirs).
import os
# Current directory
files = os.listdir('.')
print(files) # ['script.py', 'data.txt', 'subdir/']
# Specific path
files = os.listdir('/path/to/dir')
Boom, stored in files as a list. But heads up: this includes directories too, and paths are relative to the target folder. Want just files? Check os.path.isfile in a list comp:
files_only = [f for f in os.listdir('.') if os.path.isfile(f)]
It’s fast for shallow lists, cross-platform (works on Windows, Linux, macOS), and zero dependencies. Searches for “python os listdir” spike because it’s dead simple—no wonder it’s a staple.
Modern Way with pathlib
Python 3.4+ folks, meet pathlib. Ditch string juggling for Path objects—they’re smarter, chainable, and feel natural. Path.iterdir() yields paths you can collect into a list.
from pathlib import Path
dir_path = Path('/path/to/dir') # Or Path('.') for current
files = [p.name for p in dir_path.iterdir()]
print(files)
Or snag full paths:
all_paths = list(dir_path.iterdir())
file_paths = [p for p in all_paths if p.is_file()]
names = [p.name for p in file_paths]
Why switch? Path handles joins (dir_path / 'file.txt'), checks (p.exists()), and even resolves symlinks. It’s what I’d pick for new code—less error-prone than os.path hacks.
Advanced Options: glob and os.scandir
os.listdir great for basics, but patterns or efficiency? Step up.
glob.glob matches wildcards, perfect for “*.txt”:
import glob
txt_files = glob.glob('/path/to/dir/*.txt')
# Stores absolute paths in list
Recursive? **/*:
all_py = glob.glob('/project/**/*.py', recursive=True)
os.scandir (Python 3.5+) is faster—lazy iteration with stat info baked in, no extra os.stat calls.
with os.scandir('/path/to/dir') as entries:
files = [entry.name for entry in entries if entry.is_file()]
Use it for big dirs; benchmarks show 2-10x speedups over listdir.
Filtering and Edge Cases
Got picky? Filter by extension, skip hidden files (those dotfiles), or recurse.
Extensions:
from pathlib import Path
jpgs = [p for p in Path('.').iterdir() if p.suffix == '.jpg']
No hidden:
visible_files = [f for f in os.listdir('.') if not f.startswith('.')]
Subdirs? os.walk for recursion:
all_files = []
for root, dirs, files in os.walk('/start/dir'):
all_files.extend(os.path.join(root, f) for f in files)
Permissions snag you? Wrap in try-except:
try:
files = os.listdir('/protected')
except PermissionError:
print("Access denied!")
Windows backslashes? pathlib or os.path.normpath sorts it. Current date tip: Python 3.13 (out now in 2026) tweaks scandir perf even more.
Full Working Examples
Script to list, sort, and save:
import os
from pathlib import Path
def list_files(path='.'):
p = Path(path)
return sorted(p.name for p in p.iterdir() if p.is_file())
files = list_files('/your/dir')
print(files)
# Save to file
with open('filelist.txt', 'w') as f:
f.write('\n'.join(files))
Run it—tweaks for your needs. Test locally; edge cases like empty dirs return [].
Sources
- Yandex Wordstat - python список файлов
- Yandex Wordstat - python директория
- Yandex Wordstat - python os listdir
- Yandex Wordstat - python получить файлы
Conclusion
Listing files boils down to os.listdir for speed or pathlib for elegance—both dump into lists ready for action. Pick based on your Python version and needs: filter with list comps, recurse via walk, and handle quirks like permissions. You’ll handle any “list files in a directory” task like a pro, no sweat.