On this page
os.scandir
Prev: os.rmdir | Up: os | Next: os.stat
Rel: os.abort, os.access, os.chdir, os.chmod
Ref: docs.python.org — os.scandir
Tags: #public #python3 #stdlib #os
Import
import os
from os import scandir
Signature & Overview
os.scandir(path=None)
Return an iterator of DirEntry objects for given path.
Usage
import os
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
(Path(tmp) / "a.py").write_text("x=1", encoding="utf-8")
(Path(tmp) / "sub").mkdir()
with os.scandir(tmp) as it:
files = [e.name for e in it if e.is_file()]
assert files == ["a.py"]
Gotchas
- Always use
with os.scandir(...) as it:: Ensures the underlying directory file descriptor is closed promptly even if you break out of the loop early.
REPL Inspect
from os import scandir
help(scandir)
Linked from
Related notes
- tuts/python3/stdlib_module/os/rmdir Linked here; links to this page; shared tags: #os, #stdlib
- tuts/python3/stdlib_module/os/stat 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