0

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 ()
Reti43
  • 9,656
  • 3
  • 28
  • 44
superato
  • 155
  • 1
  • 1
  • 8

1 Answers1

1

Your misunderstanding probably originates from how insert() and iteration work.

Say you have a list with 3 items. When you do for item in my_list, Python will not look for how many items there are and iterate over that many indices. It will keep iterating until the list has been exhausted. When you insert an item in an index, it will push every other item in the list one index forward. So, what is at index i in the current loop, it'll be at i+1 for the next one and you'll run into it again. Here's a simple demonstration.

>>> a = [1, 2, 3]
>>> for index, item in enumerate(a):
...     print(item)
...     a.insert(index, '{0}{0}'.format(index))
...     print(a)

0
['00', 0, 1, 2]
0
['00', '11', 0, 1, 2]
0
['00', '11', '22', 0, 1, 2]
0
['00', '11', '22', '33', 0, 1, 2]
0
['00', '11', '22', '33', '44', 0, 1, 2]
0
['00', '11', '22', '33', '44', '55', 0, 1, 2]
...

Did you mean to modify the list at index i instead of inserting a new element? For example, lines[index] = split_2.

The other thing about insert() is that it modifies the list in-place and returns None as its value, which is what newlines refers to and why it's printing None. Other examples of such functions are list.append(), list.sort() and random.shuffle().

Reti43
  • 9,656
  • 3
  • 28
  • 44