Path.iterdir
iterdir() is os.listdir() that hands you Path objects already joined to the folder. It does not recurse and the order is whatever the OS returns — sort it when order matters.
Demo
from pathlib import Path for f in ['main.py', 'README.md', 'src/util.py', 'src/core.py']: Path(f).parent.mkdir(parents=True, exist_ok=True) Path(f).touch() sorted(p.as_posix() for p in Path('.').iterdir())
Listing '.' gives bare names ('src', not './src'), while listing 'src' gives 'src/util.py': each entry is the listed path joined with the name. Only one level is returned — 'src' appears as a folder, its files do not. Type a folder that does not exist and you get FileNotFoundError straight from the iterdir() call — in 3.13 the directory is read eagerly with os.scandir before any Path is returned. (The demo shows the Linux wording; Windows words the same error as [WinError 3].)
Common patterns
from pathlib import Path files = sorted(p for p in Path('inbox').iterdir() if p.is_file())
from pathlib import Path latest = max(Path('backups').iterdir(), key=lambda p: p.stat().st_mtime)
from pathlib import Path projects = [p.name for p in Path('~/code').expanduser().iterdir() if p.is_dir()]
from pathlib import Path is_empty = next(Path('queue').iterdir(), None) is None
Examples
Pitfalls
from pathlib import Path Path('src').mkdir() Path('src/app.py').touch() 'src/app.py' in list(Path('src').iterdir())
from pathlib import Path Path('src').mkdir() Path('src/app.py').touch() 'src/app.py' in sorted(p.as_posix() for p in Path('src').iterdir())
from pathlib import Path Path('a/b').mkdir(parents=True) Path('a/b/c.txt').touch() sorted(p.as_posix() for p in Path('a').iterdir())
from pathlib import Path Path('a/b').mkdir(parents=True) Path('a/b/c.txt').touch() sorted(p.as_posix() for p in Path('a').rglob('*'))
from pathlib import Path for n in ['.env', 'app.py']: Path(n).touch() sorted(p.name for p in Path('.').iterdir())
from pathlib import Path for n in ['.env', 'app.py']: Path(n).touch() sorted(p.name for p in Path('.').iterdir() if not p.name.startswith('.'))
When to use
- Listing one folder (files and sub-folders)
- Cheap emptiness checks with next(…, None)
- Recursive listings → rglob / walk
- Filtering by pattern → glob("*.csv")
Notes
FAQ
[p for p in Path(folder).iterdir() if p.is_file()] for one level; Path(folder).rglob('*') for every file and folder underneath.