|
4 | 4 | <qhelp> |
5 | 5 |
|
6 | 6 | <overview> |
7 | | -<p> If a file is opened then it should always be closed again, even if an |
8 | | -exception is raised. |
9 | | -Failing to ensure that all files are closed may result in failure due to too |
10 | | -many open files.</p> |
| 7 | +<p>When a file is opened, it should always be closed. Failure to close files could result in loss of data or resource leaks.</p> |
11 | 8 |
|
12 | 9 | </overview> |
13 | 10 | <recommendation> |
14 | 11 |
|
15 | | -<p>Ensure that if you open a file it is always closed on exiting the method. |
16 | | -Wrap the code between the <code>open()</code> and <code>close()</code> |
17 | | -functions in a <code>with</code> statement or use a <code>try...finally</code> |
18 | | -statement. Using a <code>with</code> statement is preferred as it is shorter |
19 | | -and more readable.</p> |
| 12 | +<p>Ensure that opened files are always closed, including when an exception could be raised. |
| 13 | +The best practice is to use a <code>with</code> statement to automatically clean up resources. |
| 14 | +Otherwise, ensure that <code>.close()</code> is called in a <code>try...except</code> or <code>try...finally</code> |
| 15 | +block to handle any possible exceptions. |
| 16 | +</p> |
20 | 17 |
|
21 | 18 | </recommendation> |
22 | 19 | <example> |
23 | | -<p>The following code shows examples of different ways of closing a file. In the first example, the |
24 | | -file is closed only if the method is exited successfully. In the other examples, the file is always |
25 | | -closed on exiting the method.</p> |
| 20 | +<p>In the following examples, in the case marked BAD, the file may not be closed if an exception is raised. In the cases marked GOOD, the file is always closed.</p> |
26 | 21 |
|
27 | | -<sample src="FileNotAlwaysClosed.py" /> |
| 22 | +<sample src="examples/FileNotAlwaysClosed.py" /> |
28 | 23 |
|
29 | 24 | </example> |
30 | 25 | <references> |
31 | 26 |
|
32 | | - |
| 27 | +<li>Python Documentation: <a href="https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files">Reading and writing files</a>.</li> |
33 | 28 | <li>Python Language Reference: <a href="http://docs.python.org/reference/compound_stmts.html#the-with-statement">The with statement</a>, |
34 | 29 | <a href="http://docs.python.org/reference/compound_stmts.html#the-try-statement">The try statement</a>.</li> |
35 | 30 | <li>Python PEP 343: <a href="http://www.python.org/dev/peps/pep-0343">The "with" Statement</a>.</li> |
|
0 commit comments