0

I have a txt file with multiple strings on each line as below:

Hamburger: Ground Beef, Onion, Tomato, Bread, Ketchup
Pesto_Chicken: Chicken, Peppers, Pasta, Pesto
Surf_and_Turf: Steak, Fish

I'd like to read it into my program and create a list for each line. Ideally using the first word of each line (ie Hamburger, etc.) as the list name, but that's not critical. I just need to get each line into its own list. So far I can read it in and print to the console, but not sure how to store as a list??

filepath = 'recipes.txt'
with open(filepath) as fp:
   line = fp.readline()
   cnt = 1
   while line: 
       print("Line {}: {}".format(cnt, line.strip()))
       line = fp.readline()
       cnt += 1
1
  • Lists don't have names. Dictionaries have keys. Can you display the desired output? Commented Dec 9, 2019 at 23:54

2 Answers 2

1
  • First step: split by colon parts = line.split(':')
  • Second: split the second part by comma to get the list food_list = parts[1].split(',')
  • Last step: putting it all together in a dict
foods = {} # declare a dict
with open('recipes.txt') as file:
    for line in file:
        parts = line.split(':')
        food_type = parts[0]
        food_list = parts[1].split(',')
        foods[food_type] = food_list
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! This makes sense, but I'm getting some errors still. I see that the foods matrix is created, but there's an IndexError: list index out of range at line 6 (foods_list = parts[1].split(':')
The error message does not match line 6 of the code above. In an unmodified state it runs successfully against the input.
0

give a try to the split() method which does exactly what you need.

Get the first word (as title):

parts = line.split(":")
title = parts[0]

then the other words as a list:

words_list = parts[1].split(", ")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.