List only direct report files by suffix
Also published in our Blogger archive.
A report directory may contain files, folders, and nested exports. When only its immediate CSV files are wanted, use Path.iterdir() rather than a recursive glob. The fixture creates alpha.csv and beta.txt directly in reports, then places another CSV file inside reports/nested. The comprehension accepts an entry only when is_file() is true and its final suffix is exactly .csv.
iterdir() yields immediate children, so the nested CSV is never considered. Its order is arbitrary, however, which is why the example sorts names before asserting and printing them. Path.suffix exposes the final dot-separated suffix, as described in the official pathlib reference; iterdir() and is_file() are documented in the same module. TemporaryDirectory keeps the fixture isolated and removes it after the block.
This example needs Python 3.4+ for pathlib. The suffix comparison is an exact string comparison: it does not inspect file content, treat .CSV as equivalent, or validate that a CSV is well formed. is_file() can also follow symlinks, so code with stricter link policies should account for that separately. The assertion proves the synthetic fixture’s selected names, not a claim about every filesystem layout.
AI-assistance disclosure: this article was drafted with AI assistance and should be reviewed in the context of its application.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as raw_directory:
reports = Path(raw_directory) / "reports"
reports.mkdir()
(reports / "alpha.csv").write_text("name\nAda\n", encoding="utf-8")
(reports / "beta.txt").write_text("notes\n", encoding="utf-8")
(reports / "nested").mkdir()
(reports / "nested" / "hidden.csv").write_text("name\nBo\n", encoding="utf-8")
names = sorted(
path.name
for path in reports.iterdir()
if path.is_file() and path.suffix == ".csv"
)
assert names == ["alpha.csv"]
print(", ".join(names))
alpha.csv