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

前端 未结 5 1733
独厮守ぢ
独厮守ぢ 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:58

    This is possible to read and close a file in list comprehension using the more_itertools library1:

    import more_itertools as mit
    
    lines = [line.strip() for line in mit.with_iter(open("/somefile/somewhere"))]
    

    Note more_itertools is a third-party package. Install via pip install more_itertools.

    See also the documentation for more on more_itertools.with_iter.

提交回复
热议问题