简体   繁体   中英

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 the contents to each of the two columns.

If I want to extract data listed under the column "Twitter handle", what would be the right python code to use?

thanks

with open(csvfile) as f:
    for row in 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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM