python try:except:finally

后端 未结 8 2121
后悔当初
后悔当初 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条回答
  • 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()
    
    0 讨论(0)
  • 2020-12-23 18:09

    You can do something like this:

    try:
        do_some_stuff()
    finally:
        cleanup_stuff()
    
    0 讨论(0)
提交回复
热议问题