I have a script which create a temporary text file and delete after the user close the window.
The problem is that, the temporary text file may or may not be created depending on what the user does.Or sometimes the temporary text file may be deleted before the user exit. There are three possible scenario.
- The temporary text file is created with the name of 'tempfilename'.
- The temporary text file is created with the name of 'tempfilename' but deleted before the user exit.So, when trying to remove the file it raise
OSError - The temporary text file is not created and no variable called 'tempfilename' is created, so it raise
NameError
I have tried using this code:
try:
os.remove(str(tempfilename))
except OSError or NameError:
pass
But it seems that it only catch the OSError only. Did i do something wrong?
NameError? You know that is only raised if you have a typo in your variable names, right?tempfilenamemay not be created (presumably it is created in anifstatement. I would have changed it to addtempfilename = Noneat the start and then doif tempfilename:, but it's not my codeNameErrorin that case. I am a beginner so not sure if i am doing the right way though. But whatever works.. :DNone). Not only is this cleaner IMHO, it's also less code and you can stop catchingNameErrorwhich might hide legitimate errors (e.g. typos).