I have to build a function for a grocery list from a .txt file, which looks like this:
milk
cheese
bread
hotdog buns
chicken
tuna
burgers
and so on. From the list above, my grocery list should look like [['milk', 'cheese'], ['bread', 'hotdog buns'], ['chicken', 'tuna', 'burgers']], so a list of lists in which items are separated when there is a space between them in the text file.
I have to use .readline(), and I can’t use .readlines(), .read(), or the for loop. My code right now creates an empty list:
def grocery_list(foods):
L = open(foods, 'r')
food = []
sublist = []
while L.readline() != '':
if L.readline() != '\n':
sublist.append(L.readline().rstrip('\n'))
elif L.readline() == '\n':
food.append(sublist)
sublist = []
return food
I don’t know where it goes wrong so it returns a fully empty list. I’m also not sure about the '' and '\n' part; the example test file I’m using, when opened in the shell, looks like this:
milk\n
cheese\n
\n
...
''
''
but does .rstrip() or the whole != '' make sense for every list? Or am I just not even on the right track?
One problem is that you aren’t adding the final
sublistto the result. As @Xymostech mentioned, you need to capture the result of each call toreadline()as the next call will be different. Here is how I would modify your code.Pay attention to the use of the
withstatement. This ensures that the file is closed after it is no longer needed.