2016-04-08 10 views
0

Ich möchte die quantity in derselben Zeile wie die übereinstimmende crop in einer TXT-Datei hinzufügen können. Im Moment bekomme ich den Fehler: ValueError: '(whichever string is contained within crop)' is not in list'. Ich glaube, das liegt daran, dass ich die Elemente jeder Zeile teilen muss, so dass crop nur mit dem ersten Element auf jeder Zeile verglichen wird.Wie füge ich diese Variable in dieselbe Zeile wie eine bestimmte Variable in einer TXT-Datei?

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

Antwort

0

seine nicht zu kurz/Lösung, aber es funktioniert:

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) 
Verwandte Themen