Python:搜索csv并返回整行 [英] Python: searching csv and return entire row
本文介绍了Python:搜索csv并返回整行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我找不到更好的地方问我的问题.我正在学习Python并尝试如下创建脚本.
I couldn´t find a better place to ask my question. I am learning Python and trying to create a script as follows.
1)应该能够搜索csv文件.
1) Should be able to search csv file.
2)如果找到匹配项,则返回整行.
2) Return entire row if match is found.
我的csv:
Product,Scan,Width,Height,Capacity
LR,2999,76,100,17.5
RT,2938,37,87,13.4
如果我搜索2938作为示例,则返回整行,如下所示:
If I search for 2938 for an example, entire row is returned as follows:
Product: RT
Scan: 2938
Width: 37
Height: 87
Capacity: 13,4
到目前为止,我有:
csvFile = getComponent().filePath
pos = csvFile.rfind('Desktop\\')
csvFile = csvFile[:pos] + 'programm\\products.csv'
myfile = open(csvFile)
myfile.seek(0)
for line in myfile.split('\n'):
data = line.split(',')
print data
if data[2] == agv_O_Cal.value and data[3] == agv_O_Mod.value:
print 'found: value = %s' %agv_O_Cal.value, agv_O_Mod.value
Product = data[5]
Scan = data[6]
Width = data[7]
Height = data[9]
Capacity = data[10]
print , Product, Scan, Width, Height, Capacity
该解决方案不起作用.
推荐答案
#!/usr/bin/python
import csv
import sys
#input number you want to search
number = raw_input('Enter number to find\n')
#read csv, and split on "," the line
csv_file = csv.reader(open('test.csv', "r"), delimiter=",")
#loop through the csv list
for row in csv_file:
#if current rows 2nd value is equal to input, print that row
if number == row[1]:
print (row)
这篇关于Python:搜索csv并返回整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文