简体   繁体   中英

error in while loop combined with try-except

I want to keep asking the user to enter the file name if the input entered is incorrect. I've tested the program with incorrect input (misspelt file name) but instead of asking the user to try again an error message is prompted and the program terminates. The unsuccessful code (part of if) is below. Can anyone help me to detect what's wrong?

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

It's possible to create a Path object even if the path itself does not exist in your filesystem. At some point, you need to ask the Path object if the path inside it exists in the filesystem, before exiting the while loop. You won't need the try/except block doing it like this:

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

The problem is that you are "protecting" the while loop where the name is simply asked. You could instead put the reading also inside the try / except to handle the problem:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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