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

时间:2014-08-19 11:15:35

标签: python list file python-2.7 io

我是python的新手,作为一个小项目,我正在尝试创建一个交互式程序,我可以存储食谱,每个食谱将存储为格式列表:[Name,Servings,[List成分],[方法中的步骤列表]]

创建列表的第一个函数有效(即我已创建并存储在文件[Scrambled eggs, 1, [2 eggs, milk.....], [Beat the eggs....]]

然而,当我调用'view_recipes'函数时,我得到:

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

所以它显然是在字符串中迭代字符。

如何将列表写入文件是否有问题? (我之前看过这个,每个人都说你只需要f.write(str(list))否则它必须是一个文件读取的问题:但是如何让python将其作为列表列表导入? / p>

到目前为止我的代码:

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 :(得分:0)

我认为您的问题是list(line)将字符串转换为字符列表:

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

你应该使用像pickle这样的东西来读/写数据到文件。

请参阅示例this answer

编辑:为了能够为您的文件添加更多食谱,您可以

  • 将所有食谱添加到某个变量并一次性读/写

例如

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写入文件

另外,请检查@jonrsharpe评论。您可以轻松使用sqlite3来避免我的两种方法的缺点。