2014-09-28 76 views
4

我無法找到一個更好的地方來問我的問題。我正在學習Python並試圖按如下方式創建一個腳本。Python:搜索csv並返回整行

1)應該能夠搜索csv文件。

2)如果找到匹配項,則返回整行。

我的CSV:

Product,Scan,Width,Height,Capacity 
LR,2999,76,100,17.5 
RT,2938,37,87,13.4 

如果我要尋找的2938爲例,整個行返回如下:

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 

的解決方案不起作用。

+0

什麼是您的電流輸出? – smushi 2014-09-28 06:45:50

+0

Indetation error:意外縮進 – Meigo62 2014-09-28 07:03:20

+0

剛添加答案,如果沒有意義,那麼評論 – smushi 2014-09-28 07:04:34

回答

3
#!/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 
+0

意外縮進。再次複製 – Meigo62 2014-09-28 07:13:55

+0

。修復了輕微的空間錯誤 – smushi 2014-09-28 07:14:52

+0

我的csv文件應該位於py文件所在的文件夾中嗎? – Meigo62 2014-09-28 07:17:46

0

可以使用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