0

I am making a file open function for the beginning of my program where it prompts the user to input a filename and then it will open that file. I was trying to use the try-except function for this so that if it's a valid file then print it and if its not a valid file to return a filenotfound error. I'm unsure how I can implement the file not found error. This is what I came up with so far:

def open_file():
   file = input("Please input a file to use: ")
   try:
       fp = open(file)
   except:
       filenotfounderror

I'm pretty sure this should work but I'm not sure what to write in place of the filenotfound error after except

tripleee
  • 175,061
  • 34
  • 275
  • 318
JC102
  • 5
  • 4
  • If the file couldn't be `open`ed, a `FileNotFound` error will be raised alone... You actually don't need to do anything – Tomerikoo Oct 15 '20 at 09:10

3 Answers3

0

I think the below is what you are looking for

 def open_file():
   file_name = input("Please input a file to use: ")
   try:
       fp = open(file_name)
       # do something with the file - dont forget to close it
   except FileNotFoundError:
      print(f"Wrong file or file path: {file_name}")
balderman
  • 22,927
  • 7
  • 34
  • 52
0

You don't need try/except for this; Python will raise a FileNotFoundError without your help if the file cannot be found.

What your code would do is replace every other error (permission denied, invalid file name, wrong moon phase over Redmond, etc) with FileNotFoundError. Don't do that (and generally don't use a blanket except, at least until you know exactly what you are doing).

If you want to raise an exception, the keyword for that is raise. For example;

try:
    with open(input("File: ")) as inp:
        # ... do something
except FileNotFoundError as exc:
    print("ooops, we got a", exc)
    raise ValueError("Surreptitiously replacing %s" % exc)
tripleee
  • 175,061
  • 34
  • 275
  • 318
0

This is how it should be:

def open_file():
       file = input("Please input a file to use: ")
       try:
           fp = open(file)
       except FileNotFoundError:
         print("File Not Found")
Juned Khan
  • 124
  • 1
  • 9