[Python-checkins] cpython (2.7): Issue #11426: use 'with' statements on open files in CSV examples

eli.bendersky python-checkins at python.org
Sun Mar 13 07:45:08 CET 2011


http://hg.python.org/cpython/rev/52e1ad467edd
changeset:   68419:52e1ad467edd
branch:      2.7
parent:      68410:f757b3b79c2a
user:        Eli Bendersky <eliben at gmail.com>
date:        Sun Mar 13 08:45:19 2011 +0200
summary:
  Issue #11426: use 'with' statements on open files in CSV examples

files:
  Doc/library/csv.rst

diff --git a/Doc/library/csv.rst b/Doc/library/csv.rst
--- a/Doc/library/csv.rst
+++ b/Doc/library/csv.rst
@@ -442,41 +442,44 @@
 The simplest example of reading a CSV file::
 
    import csv
-   reader = csv.reader(open("some.csv", "rb"))
-   for row in reader:
-       print row
+   with open('some.csv', 'rb') as f:
+       reader = csv.reader(f)
+       for row in reader:
+           print row
 
 Reading a file with an alternate format::
 
    import csv
-   reader = csv.reader(open("passwd", "rb"), delimiter=':', quoting=csv.QUOTE_NONE)
-   for row in reader:
-       print row
+   with open('passwd', 'rb') as f:
+       reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
+       for row in reader:
+           print row
 
 The corresponding simplest possible writing example is::
 
    import csv
-   writer = csv.writer(open("some.csv", "wb"))
-   writer.writerows(someiterable)
+   with open('some.csv', 'wb') as f:
+       writer = csv.writer(f)
+       writer.writerows(someiterable)
 
 Registering a new dialect::
 
    import csv
-
    csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
-
-   reader = csv.reader(open("passwd", "rb"), 'unixpwd')
+   with open('passwd', 'rb') as f:
+       reader = csv.reader(f, 'unixpwd')
 
 A slightly more advanced use of the reader --- catching and reporting errors::
 
    import csv, sys
-   filename = "some.csv"
-   reader = csv.reader(open(filename, "rb"))
-   try:
-       for row in reader:
-           print row
-   except csv.Error, e:
-       sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
+   filename = 'some.csv'
+   with open(filename, 'rb') as f:
+       reader = csv.reader(f)
+       try:
+           for row in reader:
+               print row
+       except csv.Error, e:
+           sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
 
 And while the module doesn't directly support parsing strings, it can easily be
 done::

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list