按名称从.csv文件中提取列

时间:2013-10-22 01:12:15

标签: python csv

我有一个像这样的.csv文件:

  Name                    |    Twitter handle
  3 Degrees Incorporation |    3Degrees_Inc

第一行是列名,第二行是两列中每一列的内容。

如果我想提取“Twitter句柄”列下列出的数据,那么使用什么是正确的python代码?

感谢

1 个答案:

答案 0 :(得分:5)

with open(csvfile) as f:
    for row in csv.DictReader(f, delimiter='|', skipinitialspace=True):
        do_something_with(row['Twitter handle']

请参阅the docs了解更多信息......但除此之外没有那么多。

但实际上,这不是一个合适的CSV,你只是很幸运,你要求最后一列,因为所有其他列都有终端空白以及初始空格,并且没有办法跳过那个。所以,如果你想处理任何其他专栏,你需要这样的东西:

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())
相关问题