1

I'm fairly new to python. I'm trying to create a function called updates. One of its arguments is a file name, called countryFileName. In my main.py I would prompt the user to enter the file name, but here in this function I need to make sure that the file name given by the user exists. If it does exist, it should then proceed to process the file. If the country file does not exist, then updates should give the user the option to quit or not, prompting y or n. If the user does not wish to quit (responds with “n”), then the function should prompt the user for the name of a new file. If the user wishes to quit (responds with a “y” or anything other than a “n”, then the method should exit and return False. The method should continue to prompt for file names until a valid file is found or the user quits. Here's what I got so far:

def updates(countryFileName):
file3 = open(countryFileName, "r")
output = open("output.txt", "w")
if file3 == None:
    # Run the loop until the user enters correct file name
    while True:
        # Prompt the user to enter the choice
        quitchoice = input("Quit? Press y for yes or y for no: ")
        if quitchoice.lower() != "n":
            output.write("The update is unsuccessful, sorry\n")
            output.close()
            return False

        elif quitchoice.lower() == "n":
            countryFileName = input("Enter new name of file: ")
            # Open the file and check status
            file2 = open(countryFileName, "r")
            if file2 != None:
                break

Right now if the user enters the wrong file name, I just get an error "No such file or directory". I'm not sure why, but I think when python gets an error at the second line file = open(countryFileName, "r") it doesn't continue to my loop. How would I solve this?

d784
  • 49
  • 1
  • 7
  • You need try/except to handle file not found. – quamrana Nov 30 '20 at 22:05
  • 4
    Does this answer your question? [How do I check whether a file exists without exceptions?](https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-without-exceptions) – atru Nov 30 '20 at 22:08

1 Answers1

0

You can try using something like:

import os, traceback

failed = 0

while 1:
  if failed:
    msg = """File doesn't exist. Please type the filename again or "n" to quit:\n"""
  else:
    msg = """Please type the filename or "n" to quit:\n"""
  
  fn = input(msg).strip()
  if fn.lower() == "n":
    break
  
  try:
    if not os.path.isfile(fn): # check if a file exists
      failed = 1
      continue
    
    with open(fn) as f:
      data = f.read()
      print(data)
      failed = 0
    
    fn = input("""Continue?\nPress "y" to continue or "enter" to quit:\n""").strip()
    if fn.lower() != "y":
      break
      
  except:
    pass
    print(traceback.format_exc())
    break

print("Bye")

Demo

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • Thanks for your example. It seems like some of your syntax is shorthand, took a while for me to figure out. Could you explain traceback? Not too familiar with that library. – d784 Nov 30 '20 at 22:38
  • `traceback` is a python builtin module that, [among other things](https://docs.python.org/3/library/traceback.html#module-traceback), can be handy to catch generic exceptions without having to expressly declare the type of exception, but you can safely remove it if you want. – Pedro Lobito Nov 30 '20 at 22:43
  • What if my initial prompt is from main.py? I'd like this function to only handle the errors as in if the file is not found. Also, if it isn't found, then I'd like to ask user to quit (y or n). How would I do that? it seems from your code the prompt is outside of the try except. – d784 Nov 30 '20 at 23:58