os.listdir
listdir gives bare names in no promised order — sort them yourself, and join them with the folder before using them. scandir is faster when you also need to know file vs folder (or the size), because the directory read already returned that information.
Demo
import os for f in ['main.py', '.env', 'docs/index.md', 'docs/api.md']: os.makedirs(os.path.dirname(f) or '.', exist_ok=True) open(f, 'w').close() try: result = sorted(os.listdir('.')) except OSError as e: result = type(e).__name__ result
listdir includes hidden names such as '.env' (it never adds '.' or '..') and mixes files and folders. A missing folder raises FileNotFoundError — the class is the same everywhere, the message text differs between Linux and Windows. In the files-only tab the names come back without their folder, so os.path.join(folder, n) is essential: isfile('app.py') would look in the current folder and say False.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| path | str | bytes | PathLike | int | no ('.') | The folder to list. bytes in → bytes names out. An open directory file descriptor also works on Unix. |
Return value
list[str] | iterator of DirEntry — listdir: the names (no '.' or '..'), in arbitrary order. scandir: an iterator of DirEntry objects (use it in a with block).
Common patterns
import os with os.scandir(path) as it: subdirs = sorted(e.name for e in it if e.is_dir())
import os images = [n for n in os.listdir(folder) if n.lower().endswith(('.png', '.jpg'))]
import os with os.scandir(folder) as it: sizes = sorted(((e.stat().st_size, e.name) for e in it if e.is_file()), reverse=True)
import os visible = [n for n in os.listdir('.') if not n.startswith('.')]
Examples
Pitfalls
import os os.mkdir('d') open('d/a.txt', 'w').close() [n for n in os.listdir('d') if os.path.isfile(n)]
import os os.mkdir('d') open('d/a.txt', 'w').close() [n for n in os.listdir('d') if os.path.isfile(os.path.join('d', n))]
import os for n in ['c', 'a', 'b']: open(n, 'w').close() len(os.listdir('.'))
import os for n in ['c', 'a', 'b']: open(n, 'w').close() sorted(os.listdir('.'))
import os open('a', 'w').close() it = os.scandir('.') first = next(it).name it.close() first
import os open('a', 'w').close() with os.scandir('.') as it: first = next(it).name first
When to use
- One folder, names only → listdir
- One folder, and you need is_dir / is_file / sizes → scandir
- A whole tree → os.walk (or Path.rglob)
- Pattern matching (*.csv) → glob.glob or Path.glob
- Object paths → Path.iterdir()
Notes
FAQ
sorted(os.listdir(folder)) for names. For files only: [n for n in os.listdir(folder) if os.path.isfile(os.path.join(folder, n))] — or with scandir: [e.name for e in os.scandir(folder) if e.is_file()].