On this page
os.listdir
Prev: os.link | Up: os | Next: os.lstat
Rel: os.abort, os.access, os.chdir, os.chmod
Ref: docs.python.org — os.listdir
Tags: #public #python3 #stdlib #os
Import
import os
from os import listdir
Signature & Overview
os.listdir(path=None)
Return a list containing the names of the files in the directory.
Usage
import os
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
(Path(tmp) / "a.txt").write_text("1", encoding="utf-8")
assert os.listdir(tmp) == ["a.txt"]
Gotchas
- Arbitrary order: Always
sorted(os.listdir(...))if deterministic ordering matters. - Prefer
os.scandir()orPath.iterdir():listdir()returns bare names (not full paths) and requires extrastat()calls to check file types.
REPL Inspect
from os import listdir
help(listdir)
Linked from
Related notes
- tuts/python3/stdlib_module/os/link Linked here; links to this page; shared tags: #os, #stdlib
- tuts/python3/stdlib_module/os/lstat Linked here; links to this page; shared tags: #os, #stdlib
- tuts/python3/stdlib_module/os Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/os/abort Linked here; shared tags: #os, #stdlib
- tuts/python3/stdlib_module/os/access Linked here; shared tags: #os, #stdlib
- tuts/python3/stdlib_module/os/chdir Linked here; shared tags: #os, #stdlib
- tuts/python3/stdlib_module/os/chmod Linked here; shared tags: #os, #stdlib
- tuts/python3/stdlib_module/os/chown shared tags: #os, #stdlib
- tuts/python3/stdlib_module/os/close shared tags: #os, #stdlib
- tuts/python3/stdlib_module/os/cpu_count shared tags: #os, #stdlib