Search code examples
pythonwhile-looptry-except

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

Solution

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