Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Fixed #18154 -- Documentation on closing File objects and best practices #140

Closed
wants to merge 1 commit into from

1 participant

Gabe Jackson
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.

Showing 1 changed file with 23 additions and 0 deletions. Show diff stats Hide diff stats

  1. 23  docs/topics/files.txt
23  docs/topics/files.txt
@@ -75,6 +75,29 @@ using a Python built-in ``file`` object::
75 75
 Now you can use any of the documented attributes and methods
76 76
 of the :class:`~django.core.files.File` class.
77 77
 
  78
+Be aware that files created in this way are not automatically closed.
  79
+The following approach may be used to close files automatically::
  80
+
  81
+    >>> from django.core.files import File
  82
+
  83
+    # Create a Python file object using open() and the with statement
  84
+    >>> with open('/tmp/hello.world', 'w') as f:
  85
+    >>>     myfile = File(f)
  86
+    >>>     for line in myfile:
  87
+    >>>         print line
  88
+    >>> myfile.closed
  89
+    True
  90
+    >>> f.closed
  91
+    True
  92
+
  93
+Closing files is especially important when accessing file fields in a loop
  94
+over a large number of objects:: If files are not manually closed after
  95
+accessing them, the risk of running out of file descriptors may arise. This
  96
+may lead to the following error:
  97
+
  98
+    IOError: [Errno 24] Too many open files
  99
+
  100
+
78 101
 File storage
79 102
 ============
80 103
 
Commit_comment_tip

Tip: You can add notes to lines in a file. Hover to the left of a line to make a note

Something went wrong with that request. Please try again.