下面的代碼背後的想法是,如果變量crop
已經包含在.txt文件中,變量quantity
將被添加到與crop
相同的行的末尾。這是我嘗試這樣做的,但它不起作用:你真的需要運行它來理解,但是,本質上,列表的錯誤部分被添加到了,不斷擴展的'/'系列出現並且行休息消失。有誰知道如何修改此代碼,使其正常工作?爲什麼不寫這個文件在python中工作?
應該怎樣輸出:
Lettuce 77 88 100
Tomato 99
實際輸出什麼:
["['\\n', 'Lettuce 77 \\n88 ', 'Tomato 88 ']100 "]
代碼:
def appendA():
with open('alpha.txt', 'r') as file_1:
lines = file_1.readlines()
for line in lines:
if crop in line:
index = lines.index(line)
line = str(line + quantity + ' ')
lines [index] = line
newlines = str(lines)
#The idea here is that the variable quantity is added onto the end
# of the same row as the entered crop in the .txt file.
with open('alpha.txt', 'w') as file_3:
file_3.write (newlines)
def appendB():
with open('alpha.txt', 'a') as file_2:
file_2.write ('\n')
file_2.write (crop + ' ')
file_2.write (quantity + ' ')
crop = input("Which crop? ")
quantity = input("How many? ")
with open('alpha.txt', 'a') as file_0:
if crop in open('alpha.txt').read():
appendA()
else:
appendB()
你可以發佈一個「示例正確的輸出」,而你取而代之嗎? – syntonym
您需要在輸入時從輸入中去除換行符,而且這不是在python中遍歷文本文件的最佳方式。 –
請勿張貼文字的屏幕截圖。這很愚蠢。 – Tomalak