2017-01-12 12 views
-2

重複としてフラグを付ける前に、私はこれに似た5つのトピックを読みましたが、動作していませんでした。変更されたCSVファイルの書き戻し方法

私はCSVファイルの値を変更することができました。しかし、私はファイル全体をどのように書き戻すのか分かりません。私は変更された行だけを書き戻すことができました。

コード:

import csv 

      file=open("stock.csv") 
      stockfile= csv.reader(file) 
      for line in stockfile: 
       if GTIN in line: 
        currentstock= line[2] 
        targetstock = line[3] 
        newstock = (int(currentstock) - int(Quantity)) 
        targetstock = str(targetstock) 
        newstock = str(newstock) 
        line[2]= int(newstock) 
        print(line) 
        with open("output.csv","w") as outfile: 
         newdata = csv.writer(outfile) 
         newdata.writerow(line) 
         if newstock<targetstock: 
          print("stock needs updating...please wait a moment") 
         else: 
          print("stock is fine") 

Stock.csv:

86947367,banana,100,40 
78364721,apple,50,20 
35619833,orange,20,30 
84716491,sweets,200,90 
46389121,chicken,40,10 

output.CSV:

86947367 banana 1 40 

(のみ変更された行ではなく、ファイルの残りの部分を書き戻します)私は欲しい:

86947367,banana,1,40 
    78364721,apple,50,20 
    35619833,orange,20,30 
    84716491,sweets,200,90 
    46389121,chicken,40,10 

ありがとうございます。

+0

在庫ファイルを1行ずつ読んでいることに気付きました。 次の条件が満たされている場合は、何もoutput.csvに書き込まれていることに気付きました。 'GTINの行:' if文に囲まれている内容をよく見てください。 – GandhiGandhi

答えて

1

あなたは何度も何度もここでは、出力ファイルを上書き:

with open("output.csv","w") as outfile: 

移動し、この行を先頭に:

with open("output.csv","w") as outfile, open("stock.csv") as infile: 
    stockfile= csv.reader(infile) 
    newdata = csv.writer(outfile) 
     for line in stockfile: 
      # ... 
      newdata.writerow(line) 
      # .... 

全作業例:

import csv 

GTIN = 'banana' 
Quantity = 99 

with open("output.csv","w") as outfile, open("stock.csv") as infile: 
    stockfile= csv.reader(infile) 
    newdata = csv.writer(outfile) 
    for line in stockfile: 
     if GTIN in line: 
      currentstock= line[2] 
      targetstock = line[3] 
      newstock = (int(currentstock) - int(Quantity)) 
      targetstock = str(targetstock) 
      newstock = str(newstock) 
      line[2]= int(newstock) 
      print(line) 
      if newstock<targetstock: 
       print("stock needs updating...please wait a moment") 
      else: 
       print("stock is fine") 
     newdata.writerow(line) 

出力:

86947367,banana,1,40 
78364721,apple,50,20 
35619833,orange,20,30 
84716491,sweets,200,90 
46389121,chicken,40,10 
+0

ありがとうございました:)私は行の行を書くことを忘れてしまった。感謝、すべての意味があります。 –

関連する問題