简体   繁体   English

使用Pathlib搜索特定的文件夹

[英]Using Pathlib to search for specific folder

I am trying to find a specific folder holding a bunch of fits files. 我试图找到一个包含一堆fits文件的特定文件夹。 The current code I have is 我当前的代码是

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'))

So if pathlib finds the wrong file fist, the user will say so and supposedly the code will then go through and search again until it finds another file with fits folders. 因此,如果pathlib找到错误的文件名,则用户会这样说,并且假定该代码将继续进行搜索,直到找到另一个带有fits文件夹的文件。 I am getting stuck in an infinite loop because it only goes down one path. 我陷入无限循环,因为它只沿着一条路径走。

I'm not quite sure I understand what you're trying to do. 我不太确定我了解您要做什么。 However, it's no wonder you're getting stuck in a loop: by re-initializing p.glob() you're starting all over again every time! 但是,也难怪您会陷入循环:通过重新初始化p.glob()您每次都会重新开始!

p.glob() is actually a generator object, which means it will keep track of its progress by itself. p.glob()实际上是一个生成器对象,这意味着它将自行跟踪其进度。 You may just use it the way it was meant to be used: by just iterating over it. 您可以按原样使用它:仅对其进行迭代。

So, for instance, you might be better served by the following: 因此,例如,以下内容可能会更好地为您服务:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM