[英]How do you draw data from a csv file, and then store it is a variable?
我正在尝试制作一个程序,让用户输入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()
下面是一个函数,它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文件是用制表符分隔的,所以我指定了它。
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。
所以,你可能现在想通了这一点,但以防万一有人还在用起来麻烦,我就想通了:与其在读者寻找行,你应该做一个新的变量(例如称为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
这将读取每一行,以查看代码是否完全显示,而不是浏览以查看代码是否独立。
我这样做的方式是这样的:
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文件中搜索它。 然后它将产品的成本保存为变量。
我希望我能帮忙。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.