Path(".").iterdir() gives every file and folder inside a folder. Keep the files with is_file(), and sort the names, because the operating system does not return them in any fixed order.
The program
python
from pathlib import Path # make a small folder to list Path("project").mkdir() Path("project/main.py").write_text("print('hi')\n") Path("project/notes.txt").write_text("todo\n") Path("project/data.csv").write_text("a,b\n") Path("project/images").mkdir() folder = Path("project") files = sorted(p.name for p in folder.iterdir() if p.is_file()) for name in files: print(name) print(f"{len(files)} files")
output
data.csv main.py notes.txt 3 files
How it works
iterdir()gives aPathfor each item in the folder, files and folders together. Theimagesfolder is left out byif p.is_file().p.nameis only the last part of the path (main.py), notproject/main.py.sorted()makes the order the same every time. Without it, the order depends on the operating system and the file system.
Only some files
glob() matches names with a pattern: * means "any characters". rglob() does the same in every subfolder too:
python
from pathlib import Path Path("project/src").mkdir(parents=True) Path("project/setup.py").write_text("") Path("project/README.md").write_text("") Path("project/src/app.py").write_text("") Path("project/src/utils.py").write_text("") folder = Path("project") print("Top level:", sorted(p.name for p in folder.glob("*.py"))) print("All:", sorted(p.as_posix() for p in folder.rglob("*.py")))
output
Top level: ['setup.py'] All: ['project/setup.py', 'project/src/app.py', 'project/src/utils.py']
as_posix() writes the path with /, so the output is the same on Windows, where paths normally use \.