Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to know why we use "with"?

>>> with open('/tmp/workfile', 'r') as f:

...     read_data = f.read()

>>> f.closed

True

1 Answer

0 votes
by (108k points)

Please be informed that in python, the 'with' keyword is used whenever we are dealing with unmanaged resources (like file streams).

It helps us to be certain that a particular resource is "cleaned up" even if exceptions are getting thrown. It is like a 'syntactic sugar' for the try/finally blocks.

You can refer to the below video tutorial for more information regarding the same:

Related questions

0 votes
1 answer
asked Sep 23, 2019 in Python by Sammy (47.6k points)
0 votes
4 answers
0 votes
1 answer
asked Mar 23, 2021 in Python by Rekha (2.2k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...