See also
rsplit
.
s = 'John,Smith,123-45-6789' fields = s.split(",") #fields is a list of 3 strings. for field in fields: print(field)
John Smith 123-45-6789
s = '"John, Jr.",Smith,123-45-6789' fields = s.split(",") #fields is a list of 4 strings. for field in fields: print(field)
"John Jr." Smith 123-45-6789
The
reader
function creates and returns an object of class
_csv.reader
.
The argument of this function must be a
list
of
str
ings
(or something like a
list
of
str
ings,
e.g., a
tuple
of
str
ings).
The argument
[s]
is a
list
of one
str
ing,
which is why we call
next
one time.
The
delimiter = ","
is unnecessary because it is the default.
import csv s = '"John, Jr.",Smith,123-45-6789' #s is a string of 29 characters. reader = csv.reader([s], delimiter = ",") #[s] is a list of 1 string. fields = next(reader) #fields is a list of 3 strings. for field in fields: print(field)
John, Jr. Smith 123-45-6789
We just used a reader to split one
str
ing.
But a reader is intended to split many
str
ings.
Let’s split two
str
ings.
Since
lines
is a
list
of two
str
ings,
we can call
next
twice.
import csv lines = [ '"John, Junior",Smith,123-45-6789', 'John III,Smith,123-45-6790' ] reader = csv.reader(lines) #lines is a list of 2 strings. fields = next(reader) #fields is a list of 3 strings. for field in fields: print(field) print() fields = next(reader) #fields is a list of 3 strings. for field in fields: print(field) print() #Let's see if we can make call next a third time. try: fields = next(reader) except StopIteration: print("Sorry, the reader is exhausted.")
John, Junior Smith 123-45-6789 John III Smith 123-45-6790 Sorry, the reader is exhausted.
Since
lines
is a
list
of two
str
ings,
the outer
for
loop will iterate twice.
Apparently, the outer
for
loop calls
next
once per iteration.
import csv lines = [ '"John, Junior",Smith,123-45-6789', 'John III,Smith,123-45-6790' ] reader = csv.reader(lines) #lines is a list of 2 strings. for fields in reader: #fields is a list of 3 strings. for field in fields: #field is a string. print(field) print() #Let's make sure the outer for loop has exhausted the reader. try: fields = next(reader) except StopIteration: print("Everything is ok. The outer for loop looped through all the lines.") else: print("Something is wrong: the outer for loop stopped too soon.")
John, Junior Smith 123-45-6789 John III Smith 123-45-6790 Everything is ok. The outer for loop looped through all the lines.