问题
When reading a CSV, instead of skipping first line (header), and reading row items by number:
with open('info.csv') as f:
reader = csv.reader(f, delimiter=';')
next(reader, None)
for row in reader:
name = row[0]
blah = row[1]
is there a built-in way to access row items by making use of header name? Something like:
with open('info.csv') as f:
reader = csv.reader(f, delimiter=';', useheader=True)
for row in reader:
name = row['name']
blah = row['blah']
where info.csv has a header line:
name;blah
John;Hello2
Mike;Hello2
回答1:
You are looking for DictReader
with open('info.csv') as f:
reader = csv.DictReader(f, delimiter=';')
for row in reader:
name = row['name']
blah = row['blah']
to quote from the link:
Create an object which operates like a regular reader but maps the information read into a dict whose keys are given by the optional fieldnames parameter. ... If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames.
回答2:
You can use a csv.DictReader instance to get this behaviour.
Example from the docs:
>>> with open('names.csv') as csvfile:
... reader = csv.DictReader(csvfile)
... for row in reader:
... print(row['first_name'], row['last_name'])
...
Eric Idle
John Cleese
回答3:
Yes, there is. That's what csv.DictReader function does - supplies the rows as an iterable of dicts.
来源:https://stackoverflow.com/questions/41567508/read-csv-items-with-column-name