Reputation: 9492
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.
OSError
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?
Upvotes: 0
Views: 180
Reputation: 4213
tempfilename = None
# ...
if tempfilename is not None and os.path.exists(tempfilename):
os.remove(tempfilename)
It's not good to catch NameError
since it will hide other typos in your code (e.g., os.remov(…)
).
Also, OSError
does not always means that the file did not exist. On Windows, if the file was in use, an exception would be raised (http://docs.python.org/2/library/os.html#os.remove). In that case, you would want to see the exception so you could be aware of the issue and/or handle it another way.
Exception handlers should be kep as narrow as possible to avoid hiding unrelated errors or bugs
Upvotes: 0
Reputation: 8610
try:
os.remove(str(tempfilename))
except (OSError, NameError):
pass
Upvotes: 3