我在csv文件中找不到第4行的总数我的代码是输入一个在csv文件中搜索的代码,然后将该代码写入一个新的csv文件,以便将其打印为收据我的问题在最后几行 这是我的密码直到你知道:
import csv
try_again= "Yes"
myfile2=open("reciept.csv","a+")
while try_again =="Yes":
found= "no"
myfile=open("stock_file.csv","r+")
gtin_8= input("enter the gtin-8")
quantity= input("enter quantity wanted")
reader=csv.reader(myfile)
for row in reader:
if gtin_8 == row[0]:
description= row[1]
unit_price= row[2]
product_price=((float(unit_price)*(float(quantity))))
product_price1= str(product_price)
new_record=(gtin_8+","+description+","+quantity+","+unit_price+","+product_price1)
myfile2.write(str(new_record))
myfile2.write("\n")
found="yes"
if found=="no":
nf="not found"
new_record1=(gtin_8+","+nf)
myfile2.write(new_record1)
myfile2.write("\n")
try_again=input("do you want to try again")
try_again=try_again.title()
myfile2.close()
myfile3=open("reciept.csv","r+")
reader1=csv.reader(myfile3)
total_cost=0
for row in reader1:
print (row)
total = sum(float(r[4]) for r in csv.reader(myfile3))
print (total_cost)
在末尾有一个嵌套循环(for循环和其中的列表理解),这就是为什么它不能像您希望的那样工作。你知道吗
您还将名为
total_cost
的变量定义为0
,并且从不对它做任何操作,然后只打印它。你知道吗不需要嵌套循环,因此应该可以:
其他指针:
还有一个^{} ,它比字符串串联和写入文件更安全。你知道吗
相关问题 更多 >
编程相关推荐