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

前端 未结 5 1736
独厮守ぢ
独厮守ぢ 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 14:52

    This is how you should do it

    with open('/somefile/somewhere') as f:
        lines = [line.strip() for line in f]
    

    In CPython the file should be closed right away as there are no references to it left, but Python language does not guarantee this.

    In Jython, the file won't be closed until the garbage collector runs

提交回复
热议问题