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

前端 未结 5 1723
独厮守ぢ
独厮守ぢ 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 will not. A context manager can be used to close it automatically. For example:

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

提交回复
热议问题