簡體   English   中英

Python編程-輸入/輸出

[英]Python Programming - input/output

我是Python的新手,我的程序需要一些幫助。 我的問題已得到解答,謝謝所有幫助我的人!

建議您不要使用自己解析文本文件的方法,而是建議您使用python標准庫中的一種現成的工具為您完成工作。 有幾種不同的可能性,其中包括configparserCSV擱置 但對於我的示例,我將使用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)

我顯然已經為您制定了一些重要的功能(例如如何顯示配方,如何重命名/編輯配方等)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM