Matt
Matt

Reputation: 13

Python Programming - input/output

I am new to Python and need some help with my program. My quesiton has now been answered, thank you to everyone who helped me!

Upvotes: 1

Views: 165

Answers (1)

ekhumoro
ekhumoro

Reputation: 120598

Rather than trying to parse a text file yourself, I would suggest you use one of the ready-made tools from the python standard library to do the work for you. There are several different possibilities, including configparser, csv, and shelve. But for my example, I will use json.

The json module allows you to save python objects to a text-file. Since you want to search for recipes by name, it would be a good idea to create a dict of recipes and then save that to a file.

Each recipe will also be a dict, and will be stored in the recipes database by name. So to start with, your input_func needs to return a recipe dict, like this:

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

Now we need a couple of simple functions for opening and saving the recipes database:

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))

And that's it! We can now put it all to work:

# 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)

I have obviously left some important features for you to work out (like how to display the recipe, how to rename/edit recipes, etc).

Upvotes: 1

Related Questions