What is the python keyword with used for

0 votes

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
Feb 9 in Python by surbhi
• 3,810 points
28 views

1 answer to this question.

0 votes
It's useful when you have two or more linked operations that you'd like to run as a pair or multiple times with a code block in between. Opening a file, modifying it, and then closing it is a classic example:

with open('output.txt', 'w') as f:

     f.write('Hi there!')

After the nested section of code, the above with statement will automatically shut the file. (Keep reading to find out how the close happens.) The benefit of using a with statement is that it guarantees that the file will be closed regardless of how the nested block exits. If an exception occurs before the end of the block, the file will be closed before an outer exception handler can catch it. If the nested block contained a return, continue, or break statement, the with statement would also shut the file automatically in those circumstances.
answered Feb 9 by CoolCoder
• 4,360 points

Related Questions In Python

0 votes
3 answers

What is the python keyword “with” used for?

The with statement in Python simplifies exception ...READ MORE

answered Jul 19, 2019 in Python by rahul
• 360 points
457 views
0 votes
1 answer

What is the python keyword "with" used for?

The PEP343 documentation contains details regarding the ...READ MORE

answered Feb 9 in Python by Dev
• 6,000 points
16 views
0 votes
1 answer

assert keyword in python is used for what purpose?

The assert keyword is used while debugging ...READ MORE

answered May 24, 2019 in Python by Taj
• 1,080 points
1,511 views
0 votes
1 answer

What is the patterns package in python used for?

Pattern is a web mining tool in ...READ MORE

answered Jul 31, 2019 in Python by Mohammad
• 3,230 points
242 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,762 views
0 votes
1 answer
0 votes
1 answer

When to use "while" or "for" in Python

Yes, there is a significant distinction between ...READ MORE

answered Feb 9 in Python by CoolCoder
• 4,360 points
40 views
0 votes
1 answer

'python' is not recognized as an internal or external command

Use "py" instead of "python" from command ...READ MORE

answered Feb 16 in Python by CoolCoder
• 4,360 points
20 views
webinar REGISTER FOR FREE WEBINAR X
Send OTP
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP