从txt中读取多行并在Python中存储到多个列表

2024-04-24 23:46:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个txt文件,每行有多个字符串,如下所示:

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

我想把它读入我的程序,并为每一行创建一个列表。理想情况下,使用每行的第一个单词(如汉堡包等)作为列表名称,但这并不重要。我只需要把每一行都放到自己的列表里。到目前为止,我可以读入并打印到控制台,但不知道如何存储为一个列表

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

Tags: 文件字符串txt列表readlinelinefpchicken
2条回答

尝试一下split()方法,它正好满足您的需要

获取第一个单词(作为标题):

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

然后列出其他单词:

words_list = parts[1].split(", ")
  • 第一步:按冒号分割parts = line.split(':')
  • 第二:用逗号分割第二部分,得到列表food_list = parts[1].split(',')
  • 最后一步:把它放在一个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

相关问题 更多 >