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

This commit is contained in:
Eli Bendersky 2011-03-13 08:45:19 +02:00
parent dd6833d20a
commit ec40bab21e
1 changed files with 21 additions and 18 deletions

View File

@ -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::