How to check if a directory contains files using Python 3

Adding to @Jon Clements’ pathlib answer, I wanted to check if the folder is empty with pathlib but without creating a set:

from pathlib import Path

# shorter version from @vogdb
is_empty = not any(Path('some/path/here').iterdir())

# similar but unnecessary complex
is_empty = not bool({_ for _ in Path('some/path/here').rglob('*')})

vogdb method attempts to iterate over all files in the given directory. If there is no files, any() will be False. We negate it with not so that is_empty is True if no files and False if files.

sorted(Path(path_here).rglob(‘*’)) return a list of sorted PosixPah items. If there is no items, it returns an empty list, which is False. So is_empty will be True if the path is empty and false if the path have something

Similar idea results {} and [] gives the same:
enter image description here

Leave a Comment