[英]How to check if a variable is the same as a line in a txt file - python
[英]How do I add this variable onto the same line as a specific variable in a .txt file?
我希望能夠將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 ()
它不是簡短/有效的解決方案,但它的工作原理是:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.