2014-03-31 143 views
1

我是Python的新手,需要我的程序帮助。我的问题现在已经得到解答,感谢所有帮助我的人!Python编程 - 输入/输出

+0

你有没有想过使用不同的文件格式?只需使用pickle,JSON,xml等等进行存储等等。它不需要那么复杂! :-) – dawg

回答

1

而不是试图解析一个文本文件自己,我会建议你使用的现成的工具之一Python标准库做的工作适合你。有几种不同的可能性,包括configparsercsvshelve。但对于我的示例,我将使用json

json模块允许您Python对象保存到一个文本文件中。由于您想按名称搜索食谱,因此创建食谱字典然后将其保存到文件将是一个好主意。

每个配方也将是一个字典,并且将存储在名称食谱数据库。因此,开始时,你input_func需要返回配方字典,像这样:

def input_func(): #defines the input_function function 
    ... 
    return { 
     'name': name, 
     'people': people, 
     'ingredients': ingredients, 
     'quantity': quantity, 
     'units': units, 
     'num_ing': num_ing, 
     } 

现在我们需要几个开简单的功能和保存食谱数据库:

def open_recipes(path): 
    try: 
     with open(path) as stream: 
      return json.loads(stream.read()) 
    except FileNotFoundError: 
     # start a new database 
     return {} 

def save_recipes(path, recipes): 
    with open(path, 'w') as stream: 
     stream.write(json.dumps(recipes, indent=2)) 

就是这样!现在,我们可以把它的所有工作:

# open the recipe database 
recipes = open_recipes('recipes.json') 

# start a new recipe 
recipe = input_func() 

name = recipe['name'] 

# check if the recipe already exists 
if name not in recipes: 
    # store the recipe in the database 
    recipes[name] = recipe 
    # save the database 
    save_recipes('recipes.json', recipes) 
else: 
    print('ERROR: recipe already exists:', name) 
    # rename recipe... 

... 

# find an existing recipe 
search_name = str(input("What is the name of the recipe you wish to retrieve?")) 

if search_name in recipes: 
    # fetch the recipe from the database 
    recipe = recipes[search_name] 
    # display the recipe... 
else: 
    print('ERROR: could not find recipe:', search_name) 

我已经明显留下了一些重要的功能,为您制定出(如如何显示的配方,如何重命名/编辑配方等)。

+0

非常感谢!这真的很有帮助。 :) – Matt

+0

@会。这可能是因为你没有先打开食谱数据库。在尝试执行搜索之前,您需要执行'recipes = open_recipes('recipes.json')'(参见我的示例代码)。 – ekhumoro