通过名称从.csv文件中提取列 [英] Extract a column from a .csv file by name

查看:135
本文介绍了通过名称从.csv文件中提取列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.csv文件,如下所示:

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.

如果我要提取 Twitter句柄列下列出的数据,将使用哪种正确的python代码?

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

谢谢

推荐答案

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

请参见该docs 以获得更多信息……但是没有比这更多的东西了。

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

但是实际上,这不是适当的CSV,您可以只是幸运的是,您要的是最后一列,因为其他所有列都具有终端空格和初始空格,因此无法跳过它。因此,如果您想处理其他任何列,则需要这样的内容:

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())

这篇关于通过名称从.csv文件中提取列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆