Back

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

What is the python keyword "with" used for?

Example from: http://docs.python.org/tutorial/inputoutput.html

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

   ... read_data = f.read() 

>>> f.closed 

True

1 Answer

0 votes
by (106k points)

The with keyword in python is used when working with unmanaged resources (like file streams). It is similar to the using statement in VB.NET and C#. It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' for try/finally blocks.

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
asked Nov 19, 2020 in Python by ashely (50.2k 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

...