Reputation: 21
I am required to include some form of error handling when the user inputs the file name such that if they put a file name which is not within the programs directory then it will appear with an error message. This is the code at the moment:
board = []
fileinput = input("Please enter your text file name:")
filename = fileinput + ".txt"
file = open(filename, "r+")
for lines in file:
board.append(list(map(int,lines.split())))
I'm not sure where to include the try/except as if I include it like this:
board = []
fileinput = input("Please enter your text file name:")
filename = fileinput + ".txt"
try:
file = open(filename, "r+")
except:
print("Error: File not found")
for lines in file:
board.append(list(map(int,lines.split())))
Then I get the following error:
line 28, in for lines in file: NameError: name 'file' is not defined
I know there probably is a very simple solution but I am struggling with wrapping my head around it.
Upvotes: 2
Views: 668
Reputation: 751
To catch exceptions from the call to open only you can add an else
clause to the end of the try
... except
statement:
try:
file = open(filename, "r+")
except:
print("Error: File not found")
else:
for lines in file:
board.append(list(map(int,lines.split())))
From the https://docs.python.org/3/tutorial/errors.html documentation:
The
try
...except
statement has an optionalelse
clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.
This ensures that we only catch errors from open
and don't incorrectly report problems with the loop reading the file contents as the file was not found.
Catching all exception types using a bare except
can also mean we incorrectly mask other errors as a missing file. It is always helpful to try and handle specific exception types (e.g. FileNotFoundError
) so we can be specific in our error messages.
try:
file = open(filename, "r+")
except FileNotFoundError:
print("Error: File not found")
except OSError as error:
print(f"Error: {error}")
else:
for lines in file:
board.append(list(map(int,lines.split())))
Additionally, so you don't forget to close the file you can use the with
statement which you can also do this without wrapping the with
block with a try
except
block:
try:
file = open(filename, "r+")
except FileNotFoundError:
print("Error: File not found")
except OSError as error:
print(f"Error: {error}")
else:
with file:
for lines in file:
board.append(list(map(int,lines.split())))
If you don't like that level of nesting, you could make the except clause return after printing an error but this depends on the flow of the rest of your program.
You may find logging.error
is a useful replacement for print
.
Upvotes: 0
Reputation: 751
You should include all lines which may occur error under try
, so:
board = []
fileinput = input("Please enter your text file name:")
filename = fileinput + ".txt"
try:
file = open(filename, "r+")
for lines in file:
board.append(list(map(int,lines.split())))
except:
print("Error: File not found")
The way you presented, the program try to ignore error and go over, which ends with NameError: name 'file' is not defined
The second problem in your case would be with scope - file
is local variable in try
and you call it outside of scope.
Upvotes: 1