10/23/26About 1 minAbout 185 words
Concept: Listing files and directories
There are two ways to list files, per folder or recursively.
The iterdir method from the pathlib library can be used to list contents of a single directory. It returns an iterator of Path objects, which can be filtered to only include files or directories.
from pathlib import Path
for path in Path('/some/dir').iterdir():
# Do something with the Path object.If the contents of the children must also be listed, the walk method can be used. It returns a list of tuples, each containing a Path object for the directory, a list of subdirectories and a list of files. The subdirectories and files are strings, not Path objects. They can be converted to Path objects by joining them with the directory path.
from pathlib import Path
for root, dirs, files in Path('/some/dir').walk():
# The dirs and files lists contain strings, not Path objects.
dir_paths = [root / d for d in dirs]
file_paths = [root / f for f in files]