我希望能够将quantity
添加到与.txt文件中匹配的crop
相同的行。但是,目前我收到错误:ValueError: '(whichever string is contained within crop)' is not in list'
。我相信这是因为我需要拆分每一行的元素,以便将crop
与每行的第一个元素进行比较。
crop = input("Which crop? ")
quantity = input("How many? ")
with open ('cropdatabase.txt', 'a+') as file:
lines = file.readlines
index = lines.index(crop)
lines[index] += ' ' + str(quantity)
file.close ()
答案 0 :(得分:0)
它不是短/有效的解决方案,但它有效:
crop = input("Which crop? ")
quantity = input("How many? ")
def crop(crop, quantity):
file = open('cropdatabase.txt',"r+")
lines = file.readlines()
linenumber = 0
for i in range(len(lines)):
if crop == lines[i].split()[0]:
linenumber = i
break
lines[linenumber] = lines[linenumber][:-1]
lines[linenumber]+= " " + str(quantity)+'\n'
text = "".join(lines)
file.close()
file2 = open('cropdatabase.txt',"w")
file2.write(text)
file2.close()
crop(crop, quantity)