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

Aug 29, 2018 in Python by bug_seeker
• 15,310 points
34 views

2 answers to this question.

0 votes

Explanation from the Preshing on Programming blog:

It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:

with open('output.txt', 'w') as f:
f.write('Hi there!')

The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.

answered Aug 29, 2018 by Priyaj
• 56,160 points
0 votes
Please visit this site to know abt "with" keyword: http://preshing.com/20110920/the-python-with-statement-by-example/
answered Aug 31, 2018 by Somesh

Related Questions In Python

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 in Python by Taj
• 840 points
18 views
0 votes
0 answers

What is the patterns package in python used for?

Can we print a half pyramid pattern ...READ MORE

Jun 25 in Python by Waseem
• 3,400 points
14 views
+1 vote
1 answer

What is the correct order to learn concepts in Python for machine learning?

Machine Learning is a vast domain. It ...READ MORE

answered Jul 25, 2018 in Python by ANMOL
• 3,620 points
49 views
+1 vote
1 answer

What is the function for Factorial in Python

Easiest way: math.factorial(x) (available in 2.6 and ...READ MORE

answered Aug 21, 2018 in Python by Priyaj
• 56,160 points

edited Aug 21, 2018 by Omkar 96 views
+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 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 124 views
+4 votes
6 answers
0 votes
1 answer

What is the flow control for “continue” in python?

This is the way "continue" statement works! You ...READ MORE

answered Jul 16, 2018 in Python by Priyaj
• 56,160 points
43 views
0 votes
1 answer

What is the Python equivalent for a case/switch statement?

if x == 'a':  # Do the ...READ MORE

answered Jul 26, 2018 in Python by Priyaj
• 56,160 points
69 views