How does python close files that have been gc'ed?

前端 未结 4 1755
栀梦
栀梦 2020-11-30 14:41

I had always assumed that a file would leak if it was opened without being closed, but I just verified that if I enter the following lines of code, the file will close:

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 15:35

    Hence the with statement.

    For Python 2.5, use

    from __future__ import with_statement
    

    (For Python 2.6 or 3.x, do nothing)

    with open( "someFile", "rU" ) as aFile:
        # process the file
        pass
    # At this point, the file was closed by the with statement.
    # Bonus, it's also out of scope of the with statement,
    # and eligible for GC.
    

提交回复
热议问题