try:
filename = input ("Please enter a file name: ")
with open(filename, 'r') as f:
text = f.read().lower()
except FileNotFoundError:
print ("File not found")
word = text.replace('!', ' ').split()
If you write the code as shown above, when you enter a file name that does not exist, the last code will be displayed UboundLocalError: local variable 'text' referenced before assignment The error appears.
So I adjusted the exception position.
try:
filename = input ("Please enter a file name: ")
with open(filename, 'r') as f:
except FileNotFoundError:
print("The file does not exist.")
text = f.read().lower()
The error expected an indented block keeps popping up. I think it's right to print out the string to enter the file name and get the name again if the exception comes out right after the with statement, but I don't know what the problem is.
python
It's a simple problem, but I wrote a code that's hard to understand the purpose, and it seems that I need to learn more about what exception handling is.
First. In the case of 'UboundLocalError: local variable 'text' referred before assignment', an exception occurs before calling text=f.read().lower()
. word = text.replace('!', ' ').This is a reference even before you assign a variable called split()
text.
Second, if an exception occurs, ignore the following line and immediately perform the exception clause. If the file is not open as shown below, do not perform text=f.read().lower()
and do print("There is no file").
and end.
try:
filename = input ("Please enter a file name: ")
with open(filename, 'r') as f:
text = f.read().lower()
except FileNotFoundError:
print("The file does not exist.")
© 2025 OneMinuteCode. All rights reserved.