2017-10-28 84 views
-2

我試圖通過.csv文件(我在Excel中打開)進行搜索並在字段中查找特定數字。我正在搜索的號碼來自GUI中的用戶輸入。如果在該字段中找到該號碼,則將輸出同一行中的其他字段中的所有項目。這是該文件的內容: screen shot of the file in excel 問題是,我似乎無法創建一段可以通過.csv讀取並查找編號的代碼。 這是我到目前爲止(這只是不工作的代碼部分):在CSV中搜索項目

def search(): # defining the function 
term=str(e3.get()) # getting the user input and setting it to the varible 'term' 
import csv # from all my researching, this is required to open the file 
open('Book1.csv') # opens the file 
# the code to look through the file would be here. It must search for the number in the correct field and output an error if it can't find it 
print() #this will print the data in the same row as the number from the different fields for the user 

如果你有一個解決方案,請給我的代碼,將盡正是我需要它去做。如果你解釋了它做了什麼,我將不勝感激,但如果你不這樣做並不重要。感謝您提前回復。

+2

歡迎來到SO。所以你想要一個答案,但不關心,如果沒有解釋?你沒有興趣學習後來自己使用它們的功能嗎? –

+0

_「給我的代碼將完成我所需要的」_堆棧溢出不是一個真正的「免費代碼寫入服務」,更多的是一個學習的地方。可能想看看[遊覽]。 – ashleedawg

+0

對不起,這兩個人說我錯誤地使用了網站,但是當我連續編寫了將近12個小時而沒有運氣的時候,我非常渴望得到答案。我將銘記未來。 – Matthew64

回答

2

你能做到這樣使用python的csv模塊:

import csv 

def search(): 
    term = #something 
    reader = csv.reader(open('Book1.csv', 'r')) 
    for row in reader: 
     if row[0] == term: 
      return row[1:] 
    return None # return None if no match 
+0

正是我需要的!我需要編輯它有點爲它與程序的其餘部分正常工作,否則我不能要求更多。非常感謝。此外,如果你可以告訴我每條線路是什麼,那麼我可以在將來使用它,我會很感激它,但不要像你必須那樣下跌。 – Matthew64

1

這裏是大熊貓的解決方案:

讓我們開始創建示例數據:

import io 
s = u"""bar_code,item,price 
1,Spam,0.1 
2,Beans,0.2 
3,Egg,0.2 
4,Milk,0.3""" 

file = io.StringIO(s) 

而現在的實際代碼:

import pandas as pd 
df = pd.read_csv(file) 
#df = pd.read_csv('Book1.csv') 

lookup = 0.2 # lookup value 
matches = df[df['price'] == lookup] # filter rows 

# if you find items 
if len(matches)>0: 
    items = matches.drop('price', axis=1).values.tolist() #drop price column 
    print(items) 
else: 
    print("No match!") 

退貨:

[[2, 'Beans'], [3, 'Egg']] 
+0

感謝您的回答,我會向任何有類似問題但不是同一問題的人推薦此答案。 – Matthew64