2016-04-08 9 views
0

quantityを.txtファイルの一致cropと同じ行に追加したいと考えています。しかし、現時点では私はエラー:ValueError: '(whichever string is contained within crop)' is not in list'を取得します。これは、cropが各行の最初の要素と比較されるように、各行の要素を分割する必要があるためです。この変数を.txtファイルの特定の変数と同じ行に追加するにはどうすればよいですか?

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

答えて

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)