使用递归文件搜索并排除带有pathlib的startswith()

Ben*_*inK 1 python operating-system for-loop pathlib

我想用 pathlib 递归搜索所有文件夹中的所有文件,但我想排除以“.”开头的隐藏系统文件 (如'.DS_Store')但我在pathlib中找不到像startswith这样的函数。如何在pathlib中实现startswith?我知道如何使用 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)
Run Code Online (Sandbox Code Playgroud)

Pet*_*ter 6

startswith()是一个Python字符串方法,请参见https://python-reference.readthedocs.io/en/latest/docs/str/startswith.html

由于您的 f 是 Path 对象,因此您必须首先通过以下方式将其转换为字符串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)
Run Code Online (Sandbox Code Playgroud)