Kaydet (Commit) ec40bab2 authored tarafından Eli Bendersky's avatar Eli Bendersky

Issue #11426: use 'with' statements on open files in CSV examples

üst dd6833d2
...@@ -442,41 +442,44 @@ Examples ...@@ -442,41 +442,44 @@ Examples
The simplest example of reading a CSV file:: The simplest example of reading a CSV file::
import csv import csv
reader = csv.reader(open("some.csv", "rb")) with open('some.csv', 'rb') as f:
for row in reader: reader = csv.reader(f)
print row for row in reader:
print row
Reading a file with an alternate format:: Reading a file with an alternate format::
import csv import csv
reader = csv.reader(open("passwd", "rb"), delimiter=':', quoting=csv.QUOTE_NONE) with open('passwd', 'rb') as f:
for row in reader: reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
print row for row in reader:
print row
The corresponding simplest possible writing example is:: The corresponding simplest possible writing example is::
import csv import csv
writer = csv.writer(open("some.csv", "wb")) with open('some.csv', 'wb') as f:
writer.writerows(someiterable) writer = csv.writer(f)
writer.writerows(someiterable)
Registering a new dialect:: Registering a new dialect::
import csv import csv
csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE) csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
with open('passwd', 'rb') as f:
reader = csv.reader(open("passwd", "rb"), 'unixpwd') reader = csv.reader(f, 'unixpwd')
A slightly more advanced use of the reader --- catching and reporting errors:: A slightly more advanced use of the reader --- catching and reporting errors::
import csv, sys import csv, sys
filename = "some.csv" filename = 'some.csv'
reader = csv.reader(open(filename, "rb")) with open(filename, 'rb') as f:
try: reader = csv.reader(f)
for row in reader: try:
print row for row in reader:
except csv.Error, e: print row
sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) 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 And while the module doesn't directly support parsing strings, it can easily be
done:: done::
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment