'with' keyword in Python

'with' keyword in Python

When I tried this keyword I wondered what could be used for that keyword, but when I found out that this is pretty much a fantastic feature given by python to use.

It is basically a shorthand for avoiding cleanup code. Suppose I am writing something in a file from my local file system -

# without 'with' keyword
f = open("test.txt", "w")
f.write("Text which I want to write.")
f.close() # cleanup code

Here we suppose to close the resource we use if we forget about it. It will cause issues that also can be written like this -

# using 'with' keyword
with open('test.txt', 'w') as f:
     f.write("Text which I want to write.")

both code snippets have the same effect on the file but in the second one, we don't need to take care of closing file resources or don't need to worry about handling cleanup code.