Skip to content

Commit 35934ff

Browse files
committed
Create not_using_with_to_open_files.rst.
1 parent e24dd4f commit 35934ff

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
Not using ``with`` to open files
2+
================================
3+
4+
Summary
5+
-------
6+
7+
Use a ``with`` statement to open a filei (e.g. ``with open("file.txt", "r" as f``). This is the standard and safest way to open a file in Python.
8+
9+
Description
10+
-----------
11+
12+
In Python 2.5, the ``file`` class was equipped with special methods that are automatically called whenever a file is opened via a ``with`` statement (e.g. ``with open("file.txt", "r") as file``). These special methods ensure that the file is properly and safely opened and closed.
13+
14+
Examples
15+
----------
16+
17+
Not using ``with`` to open a file
18+
.................................
19+
20+
The module below does not use ``with`` to open a file. This code depends on the programmer remembering to manually close the file via ``close()`` when finished. Even if the programmer remembers to call ``close()`` the code is still dangerous, because if an exception occurs before the call to ``close()`` then ``close()`` will not be called and the memory issues can occur, or the file can be corrupted.
21+
22+
.. warning:: The code below is an example of an error. Using this code will create bugs in your programs!
23+
24+
.. code:: python
25+
26+
f = open("file.txt", "r")
27+
content = f.read()
28+
1 / 0 # ZeroDivisionError
29+
f.close() # never executes, possible memory issues or file corruption
30+
31+
Solutions
32+
---------
33+
34+
Use ``with`` to open a file
35+
...........................
36+
37+
The modified module below is the safest way to open a file. The ``file`` class has some special built-in methods called ``__enter__()`` and ``__exit__()`` which are automatically called when the file is opened and closed, respectively. Python guarantees that these special methods are always called, even if an exception occurs.
38+
39+
.. code:: python
40+
41+
with open("file.txt", "r") as f:
42+
content = f.read()
43+
1 / 0 # Python still executes f.close() even though an exception occurs
44+
45+
References
46+
----------
47+
`effbot - Understanding Python's with statement <http://effbot.org/zone/python-with-statement.htm>`_

0 commit comments

Comments
 (0)