我正在尝试创建一个程序,让用户输入GTIN-8产品代码(完成),然后让程序在CSV文件中搜索它。
然后我想将匹配的产品存储在python的变量中,以便我可以累计订单的总成本并显示收据。
我在使程序将用户输入的代码与csv文件中的代码和产品相匹配时遇到问题。
这是我正在尝试的;
def checkfile(code):
import csv
with open('products.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:
file = open("products.csv", "r")
line = file.readline()
#file.close()
data = line.split(",")
#if code ==(data[0]):
if code in reader:
print("We found your product")
else:
print("We couldn't find your product")
start()
CSV文件如下所示;
65593691 500 Laminate Sheets 4.5
98593217 200 Sticky Notes 2.5
98693214 Blue Pencil Sharpener 2.1
98693399 500 Sheets of Value Paper 5
目前,该计划只是打印“我们找不到您的产品” 我需要一种方法来找到产品,打印出它的细节,然后存储为变量。
如果有人可以提供帮助,我将非常感激。
以下是我所拥有的代码,根据要求,用户输入
def start():
while True:
code = input("Please enter the product code of a product you wish to "
"add to your order:")
if len(code) == 8:
for i in code:
try:
int(i)
valid = checkvalidity(code)
except ValueError:
print("You have entered an invalid code type. Product codes "
"are 8 numbers long. Please try again.")
start()
else:
print("You have entered an invalid code type. Product codes are "
"8 numbers long. Please try again.")
start()
def checkvalidity(code):
number = code
total = (int(number[0]) * 3 + int(number[1]) +
int(number[2]) * 3 + int(number[3]) +
int(number[4]) * 3 + int(number[5]) +
int(number[6]) * 3 + int(number[7]))
if total % 10 == 0:
check = 0
print("Valid.")
checkfile(code)
else:
print("Invalid. Please try again.")
start()
答案 0 :(得分:0)
答案 1 :(得分:0)
下面是 returns
找到的数据的函数(如果有的话),这比将其存储在函数本身的(全局)变量中更好。
import csv
def checkfile(code):
found = None
with open('products.csv', newline='') as f:
reader = csv.reader(f, delimiter='\t')
for row in reader:
if row[0] == code:
print("We found your product")
found = row
break
else:
print("We couldn't find your product")
start() # ???
return found
result = checkfile('98693214') # -> We found your product
print('result: {}'.format(result)) # -> result: result: ['98693214', 'Blue Pencil Sharpener', '2.1']
result = checkfile('00000000') # -> We couldn't find your product
print('result: {}'.format(result)) # -> result: None
看起来你的csv文件是用制表符分隔的,所以我指定了它。
答案 2 :(得分:0)
def readFile(f):
o = open(f) # openFile
t = o.read()# get raw Text
l = t.split("\n") # Get lines
csv = [k.split(",") for k in t.split("\n")] # nested list of table contents
现在注意到这里有选项我认为你需要的方法更像是这样,
def readFile(f,d):
o = open(f)
r = [k.split(d) for k in o.read().split("\n")]
o.close()
return(r)
你需要通过" \ t"作为d,以便python知道使用tab作为csv文件行的分隔符。
有时在我的项目中,我将命名文件,其后缀由p:" |"定义。 ,t:" \ t",c:","其中字母表示分隔符psv csv和tsv,sv代表分隔值。但最近我一直在想json。
答案 3 :(得分:0)
所以,你现在可能已经想到了这一点,但万一有人仍然遇到问题,我只是想出来:而不是在读者中寻找行,你应该做一个读取每条单独行的新变量(例如,称为read_lines)。另外,我使用.read而不是.reader,这可能会产生影响。
#use:
reader = csv.read()
read_lines = f.readlines()
#then later:
for row in read_lines
#and
if code in read_lines
这将读取每一行,以查看代码是否完全显示而不是浏览以查看代码是否独立。
答案 4 :(得分:0)
我这样做是这样的:
with open ('Stock File.csv','r') as stock:
reader=csv.reader(stock, delimiter=',')
barcode=input('Enter the GTIN-8 code of the product you wish to purchase: ')
quantity=int(input('Enter the quantity you wish to purchase: '))
for row in reader:
if barcode in row:
cost=float(row[2])
price=quantity*cost
total=total+price
receipt.append(barcode+' '+row[1]+' '+str(quantity)+' '+row[2]+' '+str(price))
numofitems=numofitems+1
for i in range(0, numofitems):
print(str(receipt[i]))
time.sleep(0.2)
我的代码部分接受输入并在stock文件中搜索它。然后,它将产品的成本保存为变量。
我希望我能帮到你。