for line in open(filename)

后端 未结 4 446
悲&欢浪女
悲&欢浪女 2020-12-02 20:22

I frequently see python code similar to

for line in open(filename):
    do_something(line)

When does filename get closed with this code?

4条回答
  •  自闭症患者
    2020-12-02 20:51

    python is garbage-collected - cpython has reference counting and a backup cycle detecting garbage collector.

    File objects close their file handle when the are deleted/finalized.

    Thus the file will be eventually closed, and in cpython will closed as soon as the for loop finishes.

提交回复
热议问题