在Python中编写和读取文本文件列表:有更有效的方法吗?

sw1*_*456 1 python list

下面是一个程序,要求用户输入食谱并将其成分存储在一组列表中.然后程序将列表数据存储到文本文件中.如果选择选项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()
Run Code Online (Sandbox Code Playgroud)

非常感谢!

Mar*_*ers 5

您可以使用序列化格式; Python提供了几个.

对于包含字符串信息的列表或字典,我通过json模块使用JSON ,因为它是一种合理可读的格式:

import json

# writing
with open("Recipe.txt","w") as recipefile:
    json.dump({
        'name': name, 'numing': numing, 'orignumpep': orignumpep,
        'ingredient': ingredient, 'quantity': quantity, 'units': units},
        recipefile, sort_keys=True, indent=4, separators=(',', ': '))

# reading
with open("Recipe.txt") as recipefile:
    recipedata = json.load(recipefile)

# optional, but your code requires it right now
name = recipedata['name']
numing = recipedata['numing']
orignumpep = recipedata['orignumpep']
ingredient = recipedata['ingredient']
quantity = recipedata['quantity']
units = recipedata['units']
Run Code Online (Sandbox Code Playgroud)

json.dump()配置将产生非常可读的数据,最重要的是,你没有任何东西转换回整数或列表; 这一切都为你保留.