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

Python 使用带有pathlib的递归文件搜索和排除startswith(),python,for-loop,operating-system,pathlib,Python,For Loop,Operating System,Pathlib,我想用pathlib递归搜索所有文件夹中的所有文件,但我想排除以“.”开头的隐藏系统文件,如“.DS\u Store” 但是我在pathlib中找不到类似startswith的函数。如何在pathlib中实现startswith? 我知道如何使用操作系统 def recursive_file_count(scan_path): root_directory = Path(scan_path) fcount = len([f for f in root_directory.glob

我想用pathlib递归搜索所有文件夹中的所有文件,但我想排除以“.”开头的隐藏系统文件,如“.DS\u Store” 但是我在pathlib中找不到类似startswith的函数。如何在pathlib中实现startswith? 我知道如何使用操作系统

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)
startswith是一个Python字符串方法,请参见

因为f是一个Path对象,所以必须首先通过strf将其转换为字符串

我的解决方案:

有一种startswith-您可以使用pathlib.Path.is_relative_来:

pathlib.Path.is_relative_to是在Python 3.9中添加的,如果要在早期版本3.6以上的版本中使用它,则需要使用backport pathlib3x:

$> python -m pip install pathlib3x
$> python
>>> p = Path('/etc/passwd')
>>> p.is_relative_to('/etc')
True
>>> p.is_relative_to('/usr')
False
您可以在或上找到pathlib3x

但这对您的示例仍然没有帮助,因为您希望跳过以“.”开头的文件-因此您的解决方案是正确的-但效率不高:

def recursive_file_count(scan_path):
    root_directory = Path(scan_path)
    fcount = len([f for f in root_directory.glob('**/*') if not str(f.name).startswith(".")])
    print(fcount)
假设扫描路径中有200万个文件,这将创建一个包含200万个pathlib.path对象的列表。哇,那需要一些时间和记忆

对于glob函数,最好有一种类似fnmatch的过滤器或类似的东西——我正在考虑将其用于pathlib3x

glob返回需要更少内存的路径

因此,为了节省内存,解决方案可以是:

def recursive_file_count(scan_path):
    root_directory = Path(scan_path)
    fcount = 0
    # we only have one instance of f at the time
    for f in root_directory.glob('**/*'):
        if not str(f.name).startswith(".")]):
            fcount = fcount + 1
    print(count)


免责声明:我是pathlib3x库的作者。

嗨,彼得,这对我帮助很大,谢谢你的澄清!因此我能够解决它。认识到startswith是一个Python字符串方法而不是os,并且我正在使用一个path对象。
def recursive_file_count(scan_path):
    root_directory = Path(scan_path)
    fcount = len([f for f in root_directory.glob('**/*') if not str(f.name).startswith(".")])
    print(fcount)
def recursive_file_count(scan_path):
    root_directory = Path(scan_path)
    fcount = 0
    # we only have one instance of f at the time
    for f in root_directory.glob('**/*'):
        if not str(f.name).startswith(".")]):
            fcount = fcount + 1
    print(count)