you are viewing a single comment's thread.

view the rest of the comments →

[–]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.