我正在尝试搜索.csv文件(我在Excel中打开)并在字段中查找特定数字。我正在搜索的号码来自GUI中的用户输入。如果在字段中找到该号码,则将输出同一行(在其他字段中)的所有项目。这就是文件中的内容: screen shot of the file in excel 问题是我似乎无法创建一段可以通过.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
如果你有解决方案,请给我一些能完全按照我的需要去做的代码。如果你解释它做了什么,我将不胜感激,但如果不这样做则无所谓。感谢您提前回复。
答案 0 :(得分: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
答案 1 :(得分: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']]