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

前端 未结 10 1954
暖寄归人
暖寄归人 2020-12-01 11:40

I\'ve searched everywhere for this answer but can\'t find it.

I\'m trying to come up with a script that will search for a particular subfolder then check if it conta

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 12:22

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

    import pathlib
    
    root = 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.

提交回复
热议问题