Python:搜索csv并返回整行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26082360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: searching csv and return entire row
提问by Meigo62
I couldn′t find a better place to ask my question. I am learning Python and trying to create a script as follows.
我找不到更好的地方来问我的问题。我正在学习 Python 并尝试按如下方式创建脚本。
1) Should be able to search csv file.
1) 应该能够搜索 csv 文件。
2) Return entire row if match is found.
2) 如果找到匹配项,则返回整行。
My csv:
我的csv:
Product,Scan,Width,Height,Capacity
LR,2999,76,100,17.5
RT,2938,37,87,13.4
If I search for 2938 for an example, entire row is returned as follows:
如果我搜索 2938 为例,则返回整行如下:
Product: RT
Scan: 2938
Width: 37
Height: 87
Capacity: 13,4
So far I have:
到目前为止,我有:
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
The solution doesn′t work.
该解决方案不起作用。
采纳答案by smushi
#!/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', "rb"), delimiter=",")
#loop through 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
回答by Hasan Ramezani
you can use csvmodule like this:
你可以csv像这样使用模块:
import csv
reader = csv.reader(open(csvFile, 'r'))
for data in reader:
#list index start from 0, thus 2938 is in data[1]
if data[1] == agv_O_Cal.value and data[3] == agv_O_Mod.value:
#do somethinngs

