1
:これはファイルに正しく書き込まれないのはなぜですか?これを含むファイル<code>crop data.txt</code>で
Lettuce 1 2 3
Tomato 4 5 6
私が代わりに6
を除去して、それが9
と、ファイルの内容全体を置き換えるそれが必要のようなTomato
後9
を挿入するコードと入力Tomato
と9
を実行し、これは次のようなものです:
私はそれがなぜこれを行うのか、それを修正する方法はわかりません。
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"))
line_parts = line.split(" ")
print (len(line_parts))
if len (line_parts) > 4:
print('len greater')
line_parts.remove (line_parts[3])
line_parts.insert (1, quantity)
line = str(line_parts[0]+ line_parts[1] +
line_parts[2]+ line_parts[3] + ' ' + '/n')
else:
print('len less than')
line = str(quantity + " " + "\n")
lines.append(line)
with open(file, 'w') as file_rewrite:
file_rewrite.writelines(lines)
else:
print('crop not found')