2016-03-21 16 views
1

Ben csv dosyasında satır 4 toplamı bulamıyorum kodum daha sonra yeni bir csv dosyasına yazılır bir csv dosyasında aranan bir kod girmektir bunun için emir bu bilmek kadar benim kodudur benim sorunum son birkaç satır olan bir makbuz olarak basılacak: Sen (döngü ve içine bir liste anlama için) sonunda iç içe bir döngü varexcel csv dosyası python satır 4 toplamı hesaplanıyor

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) 
+0

csv csv (excel önemli değil), girintiniz yanlış – cutzero

+0

"toplam" için değer ayarlıyorsunuz, ancak "0" olarak ayarladığınız ve hiçbir zaman değiştirmediğiniz "total_cost" yazıyorsunuz. Muhtemelen 'total_cost + = sum (flo (r [4]) için csv.reader (myfile3) 'de) –

+0

evet doğrudur ama hala çalışmıyor – imeziane

cevap

0

Bu yüzden istediğin gibi çalışmıyor.

total_cost adında bir değişkeni 0 olarak tanımlayın ve hiçbir zaman bir şey yapmayın ve sonra yazdırın.

yok iç içe döngü bu çalışması gerekir böylece ihtiyaç vardır:

total_cost = 0.0 
for row in reader1: 
    if row[1] == "not found" 
     total_cost += float(row[4]) 

Diğer işaretçileri:

sadece karakter dizisi birleştirme ve bir dosyaya yazma daha kullanmak güvenlidir de bir csv.writer yoktur.

+0

hala dizin dışı – imeziane

+0

var diyor yeterli veri sütunu olmayan bir satır. – Sevanteri

+0

ne demek istiyorsun? – imeziane