vivek Posted May 5, 2020 Share Posted May 5, 2020 While learning python from w3schools, I encountered a bug in the code in the section Python Try...Except. While explaining Finally concept, there is one example given to explain the Finally block try: f = open("demofile.txt") f.write("Lorum Ipsum")except: print("Something went wrong when writing to the file")finally: f.close() #Compilation issue. Not correct This code is giving the below compilation issue Traceback (most recent call last): File "try.py", line 8, in <module> f.close() NameError: name 'f' is not defined It is because if "demofile.txt" is not present then open will failed to open and nothing will get assigned to the f. f variable will be none. So when it will execute the f.close() code written in the finally block, it will through the compilation error as it is trying to close some invalid file descriptor. Please have a look into this issue and let me know if my understanding is correct Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now