# Open new file to write
file = None
try:
file = open(filePath, \'w\')
except IOError:
msg = (\"Unable to create file on disk.\")
file.close()
return
Here is the most direct solution to your problem. I use the idiom of checking for file_obj != None
in the finally
block.
By the way, you should be aware that file
is a Python class name, so you should choose a different variable name.
file = None
try:
file = open(filePath, 'w')
except IOError:
msg = ("Unable to create file on disk.")
file.close()
return
finally:
if file != None:
file.write("Hello World!")
file.close()
You can do something like this:
try:
do_some_stuff()
finally:
cleanup_stuff()