使用pathlib递归搜索-python

问题描述 投票:0回答:1

说我有这些文件

/home/user/one/two/abc.txt
/home/user/one/three/def.txt
/home/user/one/four/ghi.txt

我正在尝试使用ghi.txt模块递归地找到pathlib。我尝试过:

p = '/home/user/'
f = Path(p).rglob(*i.txt)

但是获取文件名的唯一方法是使用列表理解:

file = [str(i) for i in f]

实际上只能运行一次。重新运行上面的命令将返回一个空列表。

我决定学习pathlib,因为显然这是社区所推荐的,但不是:

file = glob.glob(os.path.join(p,'**/*i.txt'),recursive=True) 

更直接吗?

python glob pathlib
1个回答
0
投票

您已经有了解决方案。

不确定我是否正确阅读了要求,但是我已经按照以下假设发布了答案。

  • PathListPrefix是您要搜索的起始路径全部文件。在您的情况下,可能是'/ home / user'
  • FileName是您要查找的文件的名称。您的情况是“ ghi.txt”
  • 您不希望有超过一场比赛。
  • 必须尝试使用​​pathlib模块以外的其他东西。

就直接解决方案而言,我也不确定。但是下面的解决方案是我想到的使用os模块的方法。

import os
PathListPrefix = '/home/user/'
FileName = 'ghi.txt'

def Search(StartingPath, FileNameToSearch):
    root, ext = os.path.splitext(StartingPath)
    FileName = os.path.split(root)[1]
    if FileName+ext == FileNameToSearch:
        return True
    return False

for root, dirs, files in os.walk(PathListPrefix):
    Path = root
    for eachfile in files:
        SearchPath = os.path.join(Path,eachfile)
        Found = Search(SearchPath, FileName)
        if Found:
            print(Path, FileName)
            break

该代码肯定比您的行多得多。因此它不像您的紧凑。

© www.soinside.com 2019 - 2024. All rights reserved.