簡體   English   中英

如何將此變量與.txt文件中的特定變量添加到同一行?

[英]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 ()

.txt文件的格式如下

它不是簡短/有效的解決方案,但它的工作原理是:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM