Jump to content


  • Content Count

  • Joined

  • Last visited

Community Reputation

0 Neutral

About vivek

  • Rank
  1. 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
  • Create New...