How to safely open/close files in python 2.4

前端 未结 4 2135
自闭症患者
自闭症患者 2020-11-28 08:42

I\'m currently writing a small script for use on one of our servers using Python. The server only has Python 2.4.4 installed.

I didn\'t start using Python until 2.

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 09:11

    See docs.python.org:

    When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.

    Hence use close() elegantly with try/finally:

    f = open('file.txt', 'r')
    
    try:
        # do stuff with f
    finally:
        f.close()
    

    This ensures that even if # do stuff with f raises an exception, f will still be closed properly.

    Note that open should appear outside of the try. If open itself raises an exception, the file wasn't opened and does not need to be closed. Also, if open raises an exception its result is not assigned to f and it is an error to call f.close().

提交回复
热议问题