Make hidden-file discovery explicit with glob
A file inventory can silently omit dot-prefixed entries. Choose the hidden-file policy explicitly, and use root_dir to keep results relative to the directory being inspected without changing the process working directory.
Run the example
Tested on Linux with Python 3.12.14. No third-party packages or network access are needed. In one Bash session, create a temporary working directory:
demo_start="$PWD"
demo_dir="$(mktemp -d)" || exit 1
cd -- "$demo_dir" || exit 1Save as demo_hidden_glob.py in that directory. Use this filename to avoid shadowing a standard-library module.
from glob import glob
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
root = Path(directory)
for relative in ("visible.txt", ".note.txt", ".cache/item.txt"):
path = root / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("sample\n", encoding="utf-8")
for hidden in (False, True):
matches = glob("**/*.txt", root_dir=root,
recursive=True, include_hidden=hidden)
print(f"hidden={hidden}:", sorted(matches))
print("Temporary directory removed:", not root.exists())Run it:
python3 demo_hidden_glob.pyCaptured output:
hidden=False: ['visible.txt']
hidden=True: ['.cache/item.txt', '.note.txt', 'visible.txt']
Temporary directory removed: TrueInterpret the result
Sorting is for reproducible display: glob results are not guaranteed to arrive in sorted order. Here, opting into hidden matches includes both a hidden file and a file inside a hidden directory. include_hidden was added in Python 3.11. root_dir is a search base, not a confinement mechanism; patterns and symlinks require separate policy if that matters to your application. The program creates only its own temporary fixture and removes it when the context exits. A real filesystem can change while it is being scanned.
See the version-specific Python reference for the API contract.
Clean up
In the same Bash session, remove the source file and then the empty working directory:
rm -- demo_hidden_glob.py
cd -- "$demo_start" || exit 1
rmdir -- "$demo_dir"
unset demo_start demo_dirIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.