Search code examples
pythonfor-loopoperating-systempathlib

Using recursive file search and exclude startswith() with pathlib


I want to search recursive for all files in all folders with pathlib, but I want to exclude hidden system files that start with '.' (like '.DS_Store') But I can't find a function like startswith in pathlib. How can I achieve startswith in pathlib? I know how to do it with os.

def recursive_file_count(scan_path):
    root_directory = Path(scan_path)
    fcount = len([f for f in root_directory.glob('**/*') if f.startswith(".")])
    print(fcount)

Solution

  • startswith() is a Python string method, see https://python-reference.readthedocs.io/en/latest/docs/str/startswith.html

    Since your f is a Path object, you have to convert it into a string first via str(f)

    def recursive_file_count(scan_path):
        root_directory = Path(scan_path)
        fcount = len([f for f in root_directory.glob('**/*') if str(f).startswith(".")])
        print(fcount)