You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: notebooks/beginner/file_io.ipynb
+26Lines changed: 26 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -73,6 +73,32 @@
73
73
" print(line.strip())"
74
74
]
75
75
},
76
+
{
77
+
"cell_type": "markdown",
78
+
"metadata": {},
79
+
"source": [
80
+
"The [`with`](https://docs.python.org/3/reference/compound_stmts.html#the-with-statement) statement is for obtaining a [context manager](https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers) that will be used as an execution context for the commands inside the `with`. Context managers guarantee that certain operations are done when exiting the context. \n",
81
+
"\n",
82
+
"In this case, the context manager guarantees that `simple_file.close()` is implicitly called when exiting the context. This is a way to make developers life easier: you don't have to remember to explicitly close the file you openened nor be worried about an exception occuring while the file is open. Unclosed file maybe a source of a resource leak. Thus, prefer using `with open()` structure always with file I/O.\n",
83
+
"\n",
84
+
"To have an example, the same as above without the `with`."
<p>The <ahref="https://docs.python.org/3/reference/compound_stmts.html#the-with-statement"><code>with</code></a> statement is for obtaining a <ahref="https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers">context manager</a> that will be used as an execution context for the commands inside the <code>with</code>. Context managers guarantee that certain operations are done when exiting the context.</p>
11953
+
<p>In this case, the context manager guarantees that <code>simple_file.close()</code> is implicitly called when exiting the context. This is a way to make developers life easier: you don't have to remember to explicitly close the file you openened nor be worried about an exception occuring while the file is open. Unclosed file maybe a source of a resource leak. Thus, prefer using <code>with open()</code> structure always with file I/O.</p>
11954
+
<p>To have an example, the same as above without the <code>with</code>.</p>
<spanclass="n">simple_file</span><spanclass="o">.</span><spanclass="n">close</span><spanclass="p">()</span><spanclass="c1"># This has to be called explicitly </span>
0 commit comments