首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >计算excel csv文件python中第4行的总和

计算excel csv文件python中第4行的总和
EN

Stack Overflow用户
提问于 2016-03-21 14:52:28
回答 1查看 80关注 0票数 1

我在csv文件中找不到第4行的总和,我的代码是输入一个在csv文件中搜索的代码,然后将其写入新的csv文件,以便将其打印为收据。我的问题在最后几行,这是我的代码,直到知道:

代码语言:javascript
复制
    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)
EN

回答 1

Stack Overflow用户

发布于 2016-03-21 15:02:48

最后有一个嵌套的循环(for循环和其中的列表理解),这就是它不能像您希望的那样工作的原因。

您还可以将一个名为total_cost的变量定义为0,并且从不对其执行任何操作,然后直接打印它。

不需要嵌套循环,所以这应该是可行的:

代码语言:javascript
复制
total_cost = 0.0
for row in reader1:
    if row[1] == "not found"
        total_cost += float(row[4])

其他指针:

还有一个csv.writer,它使用起来比字符串连接和写入文件更安全。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36124770

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档