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