我是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