简体   繁体   中英

Reading multiple lines from txt and storing to multiple lists in Python

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
  • 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

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(", ")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM