1
包含這個文件crop data.txt
:這爲什麼不能正確寫入文件?
Lettuce 1 2 3
Tomato 4 5 6
當我運行,而不是刪除6
和Tomato
像它應該,它與9
替換文件的全部內容之後插入9
的代碼,並輸入Tomato
和9
,所以它是這樣的:
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')