0

我正在尝试找到一个包含一堆适合文件的特定文件夹。我目前的代码是

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 找到了错误的文件,用户会这样说,并且假设代码将通过并再次搜索,直到找到另一个包含适合文件夹的文件。我陷入了无限循环,因为它只走一条路。

4

1 回答 1

0

我不太确定我理解你想要做什么。但是,难怪您会陷入循环:通过重新初始化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))
于 2018-10-22T22:27:46.443 回答