will using list comprehension to read a file automagically call close()

前端 未结 5 1734
独厮守ぢ
独厮守ぢ 2020-11-28 14:32

Does the following syntax close the file:

lines = [line.strip() for line in open(\'/somefile/somewhere\')]

Bonus points if you can demonstr

5条回答
  •  心在旅途
    2020-11-28 15:00

    It should close the file, yes, though when exactly it does so is implementation dependent. The reason is that there is no reference to the open file after the end of the list comprehension, so it will be garbage collected, and that will close the file.

    In cpython (the regular interpreter version from python.org), it will happen immediately, since its garbage collector works by reference counting. In another interpeter, like Jython or Iron Python, there may be a delay.

    If you want to be sure your file gets closed, its much better to use a with statement:

    with open("file.txt") as file:
        lines = [line.strip() for line in file]
    

    When the with ends, the file will be closed. This is true even if an exception is raised inside of it.

提交回复
热议问题