When I run the function appendA
by entering a value for crop
that is already contained within the .txt file, index
and newlines
are printed ad infinitum with index
as a sequence of ever-ascending numbers starting with 1, which alternates with newlines
being printed as 'None'. Does anyone know why this might be?
By the way the idea with newlines
is that it is a modified form of the list lines
, with split_2
being inserted at the same position (index
) as line
, replacing it.
crop = input("Which crop? ")
quantity = input("How many? ")
newlines = []
newlines = list(newlines)
def appendA ():
file_initial = open('cropdatabase.txt', 'r')
lines = file_initial.readlines()
for line in lines:
if crop in line:
index = lines.index(line)
print (index)
line = str(line)
split_2 = line.split (' ')
split_2.append (quantity + ' ')
split_2 = str(split_2)
# everything works up to here.
newlines = lines.insert (index, split_2)
print (newlines)
file.close()
def appendB ():
file = open('cropdatabase.txt', 'a+')
file.write ('\n')
file.write (crop + ' ')
file.write (quantity + ' ')
with open('cropdatabase.txt', 'a+') as file:
if crop in open('cropdatabase.txt').read():
appendA ()
else:
appendB ()
file.close ()