File open and close in python

前端 未结 2 743
忘掉有多难
忘掉有多难 2020-12-15 10:06

I have read that when file is opened using the below format

with open(filename) as f:
       #My Code
f.close()

explicit closing of file i

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-15 10:26

    Closing is not required because the with statement automatically takes care of that.

    Within the with statement the __enter__ method on open(...) is called and as soon as you go out of that block the __exit__ method is called.

    So closing it manually is just futile since the __exit__ method will take care of that automatically.

    As for the f.close() after, it's not wrong but useless. It's already closed so it won't do anything.

    Also see this blogpost for more info about the with statement: http://effbot.org/zone/python-with-statement.htm

提交回复
热议问题