What is the python “with” statement designed for?

后端 未结 10 1850
心在旅途
心在旅途 2020-11-21 07:52

I came across the Python with statement for the first time today. I\'ve been using Python lightly for several months and didn\'t even know of its existence! G

10条回答
  •  梦谈多话
    2020-11-21 08:06

    In python generally “with” statement is used to open a file, process the data present in the file, and also to close the file without calling a close() method. “with” statement makes the exception handling simpler by providing cleanup activities.

    General form of with:

    with open(“file name”, “mode”) as file-var:
        processing statements
    

    note: no need to close the file by calling close() upon file-var.close()

提交回复
热议问题