用Python编写和读取文本文件的列表:有没有更有效的方法?

2024-09-27 22:31:33 发布

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

下面是一个程序,它要求用户输入一个配方,并将其成分存储在一组列表中。然后程序将列表数据存储到文本文件中。如果选择了选项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()

非常感谢!在


Tags: 数据in列表forinputreplacequantitywrite
2条回答

如前所述,您可以使用json序列化数据,我想提到pickle模块进行序列化。 您可以使用pickle模块存储整个数据,如下所示:

import pickle
with open("Recipe.txt", "wb") as fo:
    pickle.dump((ingredient, quantity, units), fo)

和加载数据:

^{pr2}$

您可以使用序列化格式;Python提供了几种。在

对于包含字符串信息的列表或字典,我将通过^{} module使用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']

json.dump()配置将生成非常可读的数据,最重要的是,您不必将任何内容转换回整数或列表;这些都是为您保留的。在

相关问题 更多 >

    热门问题