このコードでは、対応するcrop
と同じ行にquantity
を追加してファイルに書き込みます。私のコードは、単に行の終わりまでにquantity
を追加瞬間このコードを最後の値に置き換えて新しい値を挿入するようにこのコードを変更するにはどうすればよいですか?
Tomato 2 4 1
Lettuce 3 8 7
:
これらは、テキストファイルの内容です。私がしたいのは、crop
の後に数量を挿入し、行から最後の整数を削除することです。
私はquantity
ためcrop
と「9」の入力「レタス」にした場合、それはこのようになるようそれではファイルが変更されるだろう:私はどのように本当にわからないんだけどしかし
Tomato 2 4 1
Lettuce 9 3 8
これをする。
私のコード
crop = input('Which crop? ')
quantity = input('How much? ')
file = ('cropdata.txt')
if crop in open(file).read():
with open(file, 'r') as file_read:
lines = []
for line in file_read:
if crop in line:
line = str(line.rstrip("\n") + quantity + " " + "\n")
lines.append(line)
with open(file, 'w') as file_rewrite:
file_rewrite.writelines(lines)
else:
print('Crop not found.')