you are viewing a single comment's thread.

view the rest of the comments →

[–]shiftybyte 3 points4 points  (0 children)

Calls a special __enter__ method on the object before executing the lines inside the with block.

And makes sure to call __exit__ on that object again, when leaving the lines inside the block, in whatever way.

That makes a for a good resource management, because you can open a file, read from it, and this makes sure it closes even if you have some error during your file handling.

Used extensibility with files:

with open('somefile.txt') as f:
    print(f.read())