while循环中的错误与try-except相结合

error in while loop combined with try-except

如果输入不正确,我想一直要求用户输入文件名。我用不正确的输入(拼写错误的文件名)测试了程序,但没有要求用户重试,而是提示错误消息并且程序终止。不成功的代码(if 的一部分)如下。任何人都可以帮我检测出什么问题吗?

import nltk
from nltk.tokenize import word_tokenize
import re
import os
import sys




def main():
    while True:
        try:

            file_to_open =  input("insert the file you would like to use with its extension: ")

        except FileNotFoundError:

            print("File not found.Better try again")
            continue
        else:
            break


    with open(file_to_open) as f:
        words = word_tokenize(f.read().lower())

    with open ('Fr-dictionary2.txt') as fr:
        dic = word_tokenize(fr.read().lower())

        l=[ ]
        errors=[ ]
        for n,word in enumerate (words):
            l.append(word)
            if word == "*":
                exp = words[n-1] + words[n+1]
                print("\nconcatenation trials:", exp)
                if exp in dic:
                    l.append(exp)
                    l.append("$")
                    errors.append(words[n-1])
                    errors.append(words[n+1])
                else:
                    continue

即使路径本身不存在于您的文件系统中,也可以创建路径对象。在某些时候,在退出 while 循环之前,您需要询问 Path 对象其中的路径是否存在于文件系统中。你不需要 try/except 块这样做:

while True:
    p = Path(input("please input the path: "))
    if p.exists():
        break
    print("path does not exist, try again")

问题是你是 "protecting" while 循环,其中只是询问名字。您也可以将读数也放在 try/except 中来处理问题:

while True:
   try:
       file_to_open =  input("insert the file you would like to use with its extension: ")
       with open(file_to_open) as f:
           words = word_tokenize(f.read().lower())
       break
   except FileNotFoundError:
       print("File not found.Better try again")