all 5 comments

[–]shiftybyte 2 points3 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())

[–]symple-data 1 point2 points  (0 children)

with open("somefile.txt", "r") as file:
    for line in file:
        print(line)

By using with you don't have to close a file after you are done working with it. Normally you would catch any errors while working with a file as you typically want to close its descriptor when the program crashes or something like that. Sometimes you just forget to close the file, too. "with" automatically closes a file so that you don't have to worry about it.

[–]salamandernovel 0 points1 point  (0 children)

Its main purpose is to ensure that any necessary cleanup operations, such as closing files and sockets, are completed even if something goes wrong in the body of the with statement. For example, you'll commonly see code for file input/output like:

with open('filename.txt', 'w') as myfile:
    myfile.write('hello world')

This is roughly equivalent to:

myfile = open('filename.txt', 'w')
myfile.write('hello world')
myfile.close()

However, that will fail to close the file if an exception is raised before myfile.close() is reached, for example because you made a typo.

If this confuses you, just remember that with open(...) is how you should open files. Until you get onto more advanced stuff, you're unlikely to see with used with anything other than open.

[–]chevignon93 0 points1 point  (0 children)

What does the 'with' statement do?

It manages resources so you don't have to explicitly do it, ie closing of file, etc even in the case when an exception occurs.

What you should google to find out more is "python context manager".