使用Pathlib搜索特定文件

2024-09-28 18:57:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到一个特定的文件夹保存一堆文件。我现在的代码是

redpath = os.path.realpath('.')         
thispath = os.path.realpath(redpath)         
thispath = os.path.realpath(thispath+'/../../../..')
p = Path(thispath)
userinput = 'n'
while (userinput == 'n'):
    text_file = next(p.glob('**/*.fits'))
    print("Is this the correct file path?")
    print(text_file)
    SearchedFiles = []
    SearchedFiles.append(text_file)
    userinput = input("y or n")
    if (userinput == 'n') :
        while(text_file in SearchedFiles) :
            p = Path(thispath)
            text_file = next(p.glob('**/*.fits'))

因此,如果pathlib首先找到了错误的文件,那么用户会这么说,并假设代码会再次遍历和搜索,直到找到另一个包含文件夹的文件。我陷入了一个无限循环,因为它只沿着一条路走。你知道吗


Tags: 文件path代码text文件夹osfilenext
1条回答
网友
1楼 · 发布于 2024-09-28 18:57:35

我不太明白你想做什么。 然而,难怪你会陷入一个循环:通过重新初始化p.glob(),你每次都会重新开始!你知道吗

p.glob()实际上是一个生成器对象,这意味着它将自己跟踪其进度。您可以按照它的使用方式来使用它:只需对它进行迭代。你知道吗

因此,举例来说,您可以通过以下方式得到更好的服务:

redpath = os.path.realpath('.')         
thispath = os.path.realpath(redpath)         
thispath = os.path.realpath(thispath+'/../../../..')
p = Path(thispath)
chosen = None
for text_file in p.glob('**/*.fits'):
    print("Is this the correct file path?")
    print(text_file)
    userinput = input("y or n")
    if userinput == 'y':
        chosen = text_file
        break
if chosen:
    print ("You chose: " + str(chosen))

相关问题 更多 >