python try:except:finally

后端 未结 8 2130
后悔当初
后悔当初 2020-12-23 17:36
# Open new file to write
file = None
try:
    file = open(filePath, \'w\')
except IOError:
    msg = (\"Unable to create file on disk.\")
    file.close()
    return         


        
8条回答
  •  萌比男神i
    2020-12-23 18:06

    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()
    

提交回复
热议问题