このコードを実行してcrop
とquantity
の値を入力すると、crop database.txt
に書き込まれませんが、新しい空白のテキストファイルとしてcrop database.txt
が作成されます。誰がなぜこれが分かっていますか?私はファイルを閉じる方法のためですか?誰でもこの.txtファイルへの書き込みが機能しない理由を知っていますか?
crop = input("Which crop? ")
quantity = input("How many? ")
with open ('cropdatabase.txt', 'a+') as file:
lines = file.readlines()
file.close()
with open ('cropdatabase.txt', 'a+') as file:
for row in lines:
if crop in row:
row = str(a)
split_2 = a.split (',')
split_2.append (quantity)
else:
file.write ('\n')
file.write (crop + ' ')
file.write (quantity + ' ')
file.close()
'with'を使用する場合、明示的にファイルを閉じる必要はありません。範囲外になると自動的に閉じます。 – Arpan
書き込みのコードはOKです。私は、作物と量が初期化されていることを確認するためにいくつかの印刷ステートメントを試しましたか、ifのelseブロックに入ったことはありますか? – nhouser9