Python编程-输入/输出
我是Python新手,需要一些程序帮助。我的问题现在已经得到了回答,谢谢所有帮助我的人 与其自己解析文本文件,不如使用python标准库中现成的工具来完成这项工作。有几种不同的可能性,包括和。但以我为例,我将使用Python编程-输入/输出,python,file,text,Python,File,Text,我是Python新手,需要一些程序帮助。我的问题现在已经得到了回答,谢谢所有帮助我的人 与其自己解析文本文件,不如使用python标准库中现成的工具来完成这项工作。有几种不同的可能性,包括和。但以我为例,我将使用 json模块允许您将python对象保存到文本文件中。由于您希望按名称搜索食谱,因此最好创建一份食谱目录,然后将其保存到文件中 每个配方也将是一个dict,并将按名称存储在配方数据库中。因此,首先,您的input_func需要返回一个配方dict,如下所示: def input_fun
json
模块允许您将python对象保存到文本文件中。由于您希望按名称搜索食谱,因此最好创建一份食谱目录,然后将其保存到文件中
每个配方也将是一个dict,并将按名称存储在配方数据库中。因此,首先,您的input_func
需要返回一个配方dict,如下所示:
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)
很明显,我给您留下了一些重要的功能(如如何显示配方、如何重命名/编辑配方等)。您是否考虑过使用不同的文件格式?只需使用pickle、JSON、xml等进行存储即可。它不需要如此复杂!:-)谢谢!这真的很有帮助。:)@威尔。那可能是因为你没有先打开食谱数据库。在尝试执行搜索之前,您需要执行
recipes=open_recipes('recipes.json')
(参见我的示例代码)。