mirror of
https://github.com/python/cpython.git
synced 2025-10-01 12:52:18 +00:00
Issue #11426: use 'with' statements on open files in CSV examples
This commit is contained in:
parent
dd6833d20a
commit
ec40bab21e
1 changed files with 21 additions and 18 deletions
|
@ -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::
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue