Predefined Clean-up Actions

Look at the following code, which tries to open a file and print its contents to the screen.

for line in open("myfile.txt") :
    print(line, end="")        

But the problem is that it leaves the file open after it finishes, which could cause problems if the program is large.

That's why we use this code:

with open("myfile.txt") as file :
    for line in file :
        print(line, end="")        

The idea here is that the with statement opens the file and ensures it gets closed by itself once it finishes reading the lines, even if an issue occurs. So, as soon as the with block is done, the file gets closed immediately, and you don't have to worry about anything.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了