如何将此变量添加到.txt文件中特定变量的同一行?

时间:2016-04-08 11:51:09

标签: python text-files

我希望能够将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 ()

The .txt file is formatted like this

1 个答案:

答案 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)