我是Python的新手,需要我的程序帮助。我的问题现在已经得到解答,感谢所有帮助我的人!Python编程 - 输入/输出
1
A
回答
1
而不是试图解析一个文本文件自己,我会建议你使用的现成的工具之一Python标准库做的工作适合你。有几种不同的可能性,包括configparser,csv和shelve。但对于我的示例,我将使用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)
我已经明显留下了一些重要的功能,为您制定出(如如何显示的配方,如何重命名/编辑配方等)。
相关问题
- 1. Python编程空白输出
- 2. Python输入和输出线程
- 3. Python输入/输出,文件
- 4. 输入和输出程序
- 5. 输入,输出,输入/输出参数
- 6. Python程序不使用输入输入()
- 7. Python Cyrilic编码输出
- 8. 输入和输出文件python
- 9. python多输入和多输出
- 10. 如何在python中输入后输出?
- 11. Python错误的输出输入框
- 12. Python Tkinter窗口输出和Shell输入
- 13. tkinter在Python中的输入输出3
- 14. 如何在python中输出输入
- 15. 检索python输出为c#输入
- 16. Python读取输出声音不输入
- 17. 编译猪举动输出到输入
- 18. 使用缓冲区竞争编程的Python快速输入输出
- 19. 输入输出程序不会在python 3中输出正确的整数
- 20. 输入输出
- 21. Python嵌入变量输出
- 22. 深入Python输出错误
- 23. python写入输出文件
- 24. 输入和输出
- 25. 在python中输入输入?
- 26. Python控制台应用程序 - 输入行以上输出
- 27. 将Python输入输出到C程序中
- 28. 我的python程序得到输入和输出为空
- 29. python pipe子进程在套接字上的输入/输出
- 30. Python:同步线程之间的输入和输出
你有没有想过使用不同的文件格式?只需使用pickle,JSON,xml等等进行存储等等。它不需要那么复杂! :-) – dawg