Skip to main content
 首页 » 编程设计

python之在 Python 中将列表写入和读取文本文件 : Is there a more efficient way

2025年05月04日13cyq1162

<分区>

下面是一个程序,它要求用户输入食谱并将其成分存储在一组列表中。然后程序将列表数据存储到一个文本文件中。如果选择选项 2,它将从文本文件中检索存储的数据并将其加载回程序进行处理并显示给用户。

文本文件不需要以人类可读的格式存储数据,但在检索后,它必须采用一种格式,其中每个列表项都可以识别,并且数量值需要能够进行计算。

我的方法是轻松地将列表转储到文本文档中。检索数据时,它首先将每一行添加到一个变量,删除方括号、语音标记等,然后将其拆分回列表。

这些似乎是一种相当冗长且低效的方法。肯定有一种更简单的方法可以将列表数据存储到文件中,然后直接检索回列表中吗?

那么,有没有更简单高效的方法呢? 或者,有没有更简单/更有效的替代方法?

while True: 
 
    print("1: Enter a Recipe") 
    print("2: Calculate Your Quantities") 
    option = input() 
    option = int(option) 
 
    if option == 1: 
 
      name = input("What is the name of your meal?: ") 
      numing = input("How many ingredients are there in this recipe?: ") 
      numing = int(numing) 
      orignumpep = input("How many people is this recipe for?: ") 
 
 
      ingredient=[] 
      quantity=[] 
      units=[] 
 
      for x in range (0,numing): 
            ingr = input("Type in your ingredient: ") 
            ingredient.append(ingr) 
            quant = input("Type in the quantity for this ingredient: ") 
            quantity.append(quant) 
            uni = input("Type in the units for this ingredient: ") 
            units.append(uni) 
 
      numing = str(numing) 
      ingredient = str(ingredient) 
      quantity = str(quantity) 
      units = str(units) 
 
      recipefile = open("Recipe.txt","w") 
      recipefile.write(name) 
      recipefile.write("\n") 
      recipefile.write(numing) 
      recipefile.write("\n") 
      recipefile.write(orignumpep) 
      recipefile.write("\n") 
      recipefile.write(ingredient) 
      recipefile.write("\n") 
      recipefile.write(quantity) 
      recipefile.write("\n") 
      recipefile.write(units) 
      recipefile.close() 
 
    elif option == 2: 
        recipefile = open("Recipe.txt") 
        lines = recipefile.readlines() 
        name = lines[0] 
        numing = lines[1] 
        numing = int(numing) 
        orignumpep = lines[2] 
        orignumpep = int(orignumpep) 
 
        ingredients = lines[3].replace("/n", "").replace("[", "").replace("]","").replace("'", "").replace(",", "") 
        quantitys = lines[4].replace("/n", "").replace("[", "").replace("]","").replace("'", "").replace(",", "") 
        unitss = lines[5].replace("/n", "").replace("[", "").replace("]","").replace("'", "").replace(",", "") 
 
        ingredient=[] 
        quantity=[] 
        units=[] 
 
        ingredient = ingredients.split() 
        quantity = quantitys.split() 
        units = unitss.split() 
 
 
        for x in range (0,numing): 
             quantity[x] = int(quantity[x]) 
 
        numberpep = input("How many people is the meal for?") 
        numberpep = int(numberpep) 
 
        print("New Ingredients are as follows...") 
 
        for x in range (0,numing): 
            print(ingredient[x], " ", quantity[x]/orignumpep*numberpep, units[x]) 
 
input() 

非常感谢!