没有标头的Python csv [英] Python csv without header

查看:67
本文介绍了没有标头的Python csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用csv文件中的标头信息,可以将城市抓取为:

With header information in csv file, city can be grabbed as:

city = row['city']

现在如何假定csv文件没有标题,只有1列,而列是city.

Now how to assume that csv file does not have headers, there is only 1 column, and column is city.

推荐答案

如果您自己声明标题,则仍然可以使用您的行,因为您知道它:

You can still use your line, if you declare the headers yourself, since you know it:

with open('data.csv') as f:
    cf = csv.DictReader(f, fieldnames=['city'])
    for row in cf:
        print row['city']

有关更多信息,请检查文档中的 csv.DictReader 信息.

For more information check csv.DictReader info in the docs.

另一种选择是只使用位置索引,因为您知道只有一列:

Another option is to just use positional indexing, since you know there's only one column:

with open('data.csv') as f:
    cf = csv.reader(f)
    for row in cf:
        print row[0]

这篇关于没有标头的Python csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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