在CSV列中查找值,返回值的行号 [英] Find value in CSV column, return line number of the value

查看:245
本文介绍了在CSV列中查找值,返回值的行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含内容的CSV文件:

I have a CSV file with contents:

scenario1,5,dosomething
scenario2,10,donothing
scenario3,8,dosomething
scenario4,5,donothing

我想获取变量的内容,首先查看它是否在第一列中(如果为true的话)-我想获取找到该行的行号以及整个行的内容. csv的第1列中将没有重复的值.

I would like to take the contents of a variable to firstly see if it is in the first column, if true - I would like to get the row number where it is found and the entire line contents. There will be no duplicate values in column 1 of the csv.

我可以部分地执行第一步,即查找变量是否在csv中,并返回整行.

I can partly do the first step which is to find if the variable is in the csv, returning the whole line.

import csv
filename = csv.reader(open('/file.csv', "rb"), delimiter=",")
v = 'scenario1'
for row in configfile:
    if 'v' in row[0]:
        print row

我收到的结果是:

['scenario1','5','dosomething']

但是我需要第二部分的帮助.这是查找行号.

But I need assistance with the second part please. This is to find the row number.

推荐答案

尝试一下:

import csv
with open("ooo.csv", "r") as f:
    reader = csv.reader(f)
    for line_num, content in enumerate(reader):
        if content[0] == "scenario1":
            print content, line_num + 1

或者没有csv模块:

with open("ooo.csv") as f:
    for l, i in enumerate(f):
        data = i.split(",")
        if data[0] == "scenario1":
            print data, l + 1

输出:

['scenario1', '5', 'dosomething'] 1

这篇关于在CSV列中查找值,返回值的行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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