将包含列表的列表写入文件,然后再读取

0 投票
1 回答
896 浏览
提问于 2025-04-18 17:47

我刚开始学习Python,作为一个小项目,我想做一个互动程序,用来存储食谱。每个食谱会以这样的格式存储: [名称, 份量, [材料列表], [步骤列表]]

我写的第一个函数可以创建这个列表(也就是说,我已经创建并存储了一个文件,内容是 [炒鸡蛋, 1, [2个鸡蛋, 牛奶.....], [打鸡蛋....]])。

但是当我调用 'view_recipes' 函数时,我得到了:

Name:  [
Servings:  '
Ingredients:
S
Method:
c

所以很明显,它是在逐个字符地遍历字符串。

这是不是我把列表写入文件时出的问题?(我之前查过,大家都说只需要用 f.write(str(list)) 就可以了。否则可能是读取文件时出的问题:那我该怎么让Python把它导入为一个列表的列表呢?

到目前为止我的代码是:

import re
#Input file
f = open("bank.txt", "r+")

def add_recipe():
    recipe = []
    ingredients = []
    method = []
    #recipe = [name, servings, ingredients(as list), method(as list)]
    recipe.append(raw_input("Please enter a name for the dish: "))
    recipe.append(raw_input("How many servings does this recipe make? "))
    print "Ingredients"
    ans = True
    while ans:
        i = raw_input("Enter amount and ingredient name i.e. '250g Flour' or 'x' to continue: ")
        if i.lower() == "x":
            ans = False
        else:
            ans = False
            ingredients.append(i)
            ans = True
    print "Ingredients entered: "
    for ing in ingredients:
        print ing
    recipe.append(ingredients)
    print "Method: "
    ans2 = True
    while ans2:
        j = raw_input("Type next step or 'x' to end: ")
        if j.lower() == "x":
            ans2 = False
        else:
            ans2 = False
            method.append(j)
            ans2 = True
    print "Method: "
    for step in method:
        print step
    recipe.append(method)
    print "Writing recipe information to file..."
    print recipe
    f.write(str(recipe))
    f.write("\n")

def view_recipes():
    for line in f:
        print "Name: ", list(line)[0]
        print "Servings: ", list(line)[1]
        print "Ingredients: "
        for k in list(line)[2]:
            print k
        print "Method: "
        for l in list(line)[3]:
            print l

1 个回答

0

我觉得你的问题在于,list(line) 这个操作会把一个字符串变成一个字符列表:

>>> l = "abc"
>>> list(l)
['a', 'b', 'c']

你应该使用像 pickle 这样的工具来读写文件中的数据。

比如可以参考一下 这个回答

补充一下:如果你想在文件中添加更多的食谱,你可以

  • 把所有的食谱放到一个变量里,然后一次性读写所有的内容

比如可以这样做:

recipes = []
want_to_add_recipe = True
while want_to_add_recipe:
    recipes.append(add_recipe())
    ans = raw_input('more? ')
    want_to_add_recipe = True if ans == 'y' else False
with open("Recipe.txt", "wb") as fo:
    pickle.dump(recipe, fo)

add_recipe 函数中:

with open("Recipe.txt", "rb") as fo:
    recipes = pickle.load(fo)
for name, serving, ingredients, method in recipes:
    #print things        

你需要把 add_recipe 改成 return recipe

  • 每次调用 add_recipe 时,都要把食谱添加到你的文件中:
    • 先读取你的文件
    • 如果有的话,加载 recipes
    • 把你的食谱添加到 recipes
    • 把新的 recipes 写回文件

另外,看看 @jonrsharpesqlite3 来避免我提到的两种方法的缺点。

撰写回答