How to check to see if a folder contains files using python 3 How to check to see if a folder contains files using python 3 python python

How to check to see if a folder contains files using python 3


'files' already tells you whats in the directory. Just check it:

for dirpath, dirnames, files in os.walk('.'):    if files:        print(dirpath, 'has files')    if not files:        print(dirpath, 'is empty')


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 @vogdbis_empty = not any(Path('some/path/here').iterdir())# similar but unnecessary complexis_empty = not bool(sorted(Path('some/path/here').rglob('*')))

vogdb method attempts iterates 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


You can make use of the new pathlib library introduced in Python 3.4 to extract all non-empty subdirectories recursively, eg:

import pathlibroot = pathlib.Path('some/path/here')non_empty_dirs = {str(p.parent) for p in root.rglob('*') if p.is_file()}

Since you have to walk the tree anyway, we build a set of the parent directories where a file is present which results in a set of directories that contain files - then do as you wish with the result.