Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read CSV items with column name

Tags:

python

csv

When reading a CSV, instead of skipping the 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 the header line? 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

like image 207
Basj Avatar asked Jan 10 '17 11:01

Basj


People also ask

How do you add a column name to a reading CSV?

names parameter in read_csv function is used to define column names. If you pass extra name in this list, it will add another new column with that name with NaN values. header=None is used to trim column names is already exists in CSV file.


3 Answers

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.

like image 153
e4c5 Avatar answered Oct 20 '22 14:10

e4c5


You can use a csv.DictReader instance to get this behaviour.

Example from the docs:

>>> with open('names.csv', newline='') as csvfile:
...     reader = csv.DictReader(csvfile)
...     for row in reader:
...         print(row['first_name'], row['last_name'])
...
Eric Idle
John Cleese

The reader generates the dictionary keys from the first row of the csv file automatically. If the csv file does not contain a header row you can set the keys by passing a list to the DictReader:

fieldnames = ['first_name', 'last_name']
reader = csv.DictReader(csvfile, fieldnames=fieldnames)
like image 36
snakecharmerb Avatar answered Oct 20 '22 12:10

snakecharmerb


Yes, there is. That's what csv.DictReader function does - supplies the rows as an iterable of dicts.

like image 7
Moses Koledoye Avatar answered Oct 20 '22 14:10

Moses Koledoye