[英]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.