What is the python “with” statement designed for?

后端 未结 10 1817
心在旅途
心在旅途 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:12

    An example of an antipattern might be to use the with inside a loop when it would be more efficient to have the with outside the loop

    for example

    for row in lines:
        with open("outfile","a") as f:
            f.write(row)
    

    vs

    with open("outfile","a") as f:
        for row in lines:
            f.write(row)
    

    The first way is opening and closing the file for each row which may cause performance problems compared to the second way with opens and closes the file just once.

提交回复
热议问题