From ec40bab21ebc5758cf28325355f08d98e566979a Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Sun, 13 Mar 2011 08:45:19 +0200 Subject: [PATCH] Issue #11426: use 'with' statements on open files in CSV examples --- Doc/library/csv.rst | 39 +++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/Doc/library/csv.rst b/Doc/library/csv.rst index 03941708ea3..f4e9d7cb940 100644 --- a/Doc/library/csv.rst +++ b/Doc/library/csv.rst @@ -442,41 +442,44 @@ Examples 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::