阅读csv,然后枚举 [英] Read csv, then enumerate

查看:99
本文介绍了阅读csv,然后枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我的代码中直接有一个列表,并且正在使用枚举,因此我可以使用列表索引号为用户选择其中一项.看起来像这样(只包括标题行)

At the moment, I have a list directly in my code and am using enumerate so I can use the list index numbers for the user to select one of the items. Looks like this (just header row included)

fmpList = [['Date', 'ID', 'Plot No', 'Modified', 'Lat', 'Long']......
for item in enumerate(fmpList[]):            
    print "[%d] %s" % item

这很好用,但我不想将列表放在函数中,而是从文件中读取csv.我用来做这件事的替代方法是...

This works well but I don't want to put the list in the function but rather to read the csv from file. The alternative I used to do this is...

import csv
with open ('fmpList.csv', 'rU') as csvfile: 
        next (csvfile, None)
        plotlist = csv.reader(csvfile, delimiter=',', dialect=csv.excel_tab)
        for row in enumerate (plotlist):
            print '[%s]' %(item[2])

这也可以,但是我似乎无法结合使用2 ...读取csv文件,然后枚举能够基于索引进行选择. 帮助将不胜感激

This also works but I can't seem to combine the 2... read the csv file in, then enumerate to be able to have a selection based on index. Help would be greatly appreciated

所以现在我有了想要的工作代码...

So now I've got working code as I wanted...

import csv
with open ('fmpList.csv', 'rU') as csvfile: 
        next (csvfile, None)
        plotlist = csv.reader(csvfile, delimiter=',', dialect=csv.excel_tab)
        for row in enumerate (plotlist):
            print '[%s]' %(item[2])

但是最后一行没有显示第二列.实际上,我位于第0列(索引编号)和第2列(绘图名称)之后. [0]给出第一列...很酷,但是任何大于1的数字都会给出IndexError:..out of range.尝试了所有组合,但无济于事

But the last line is not giving me column 2 only displayed. In fact, I'm after column 0 (the index no) and 2 (the plot name). [0] gives the first column...cool, but any number greater than 1 gives IndexError: ..out of range. Tried every combo but nothing works

推荐答案

enumerate(...)适用于任何可迭代的

import csv
with open ('fmpList.csv', 'rU') as csvfile: 
    next(csvfile, None) # skip header
    plotlist = csv.reader(csvfile, delimiter=',', dialect=csv.excel_tab)
    for i, row in enumerate(plotlist):
        print "[%d] %s" % (i, row)

这篇关于阅读csv,然后枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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