Skip to content Skip to sidebar Skip to footer

Extract A Column From A .csv File By Name

I have an .csv file like this: Name | Twitter handle 3 Degrees Incorporation | 3Degrees_Inc the first row is the column names and the second row is th

Solution 1:

withopen(csvfile) as f:
    forrowin csv.DictReader(f, delimiter='|', skipinitialspace=True):
        do_something_with(row['Twitter handle']

See the docs for more information… but there's not that much more to it than this.

But really, this isn't a proper CSV, and you're just getting lucky that you're asking for the last column, because all the other columns have terminal whitespace as well as initial whitespace, and there's no way to skip that. So, if you wanted to handle any other column, you'd need something like this:

with open(csvfile) as f:
    headers = next(csv.reader(f, delimiter='|', skipinitialspace=True))
    headers = [header.strip() for header in headers]
    for row in csv.DictReader(f, fieldnames=headers, 
                              delimiter='|', skipinitialspace=True):
        do_something_with(row[colname].strip())

Post a Comment for "Extract A Column From A .csv File By Name"