1

Below is a program which asks the user to enter a recipe and stores their ingredients in a set of lists. The program then stores the list data into a text file. If option 2 is chosen it will retrieve the stored data from the text file and load it back into the program for processing and to be displayed to the user.

The text file doesn't need to store data in a human readable format but after retrieval it must be in a format where each list item can be identifiable and the quantities values need to be able to undergo a calculation.

My method was to dump the lists into a text document easily. When retrieving the data it first adds each line to a variable, removes the square brackets, speech marks etc and then splits it back into a list.

These seems to be a rather long winded and inefficient way of doing it. Surely there is an easier way to store list data into a file and then retrieve straight back into a list?

So, is there an easier more efficient way? Or, is there an alternative method which is again more simple / efficient?

while True:

    print("1: Enter a Recipe")
    print("2: Calculate Your Quantities")
    option = input()
    option = int(option)

    if option == 1:

      name = input("What is the name of your meal?: ")
      numing = input("How many ingredients are there in this recipe?: ")
      numing = int(numing)
      orignumpep = input("How many people is this recipe for?: ")


      ingredient=[]
      quantity=[]
      units=[]

      for x in range (0,numing):
            ingr = input("Type in your ingredient: ")
            ingredient.append(ingr)
            quant = input("Type in the quantity for this ingredient: ")
            quantity.append(quant)
            uni = input("Type in the units for this ingredient: ")
            units.append(uni)

      numing = str(numing)
      ingredient = str(ingredient)
      quantity = str(quantity)
      units = str(units)

      recipefile = open("Recipe.txt","w")
      recipefile.write(name)
      recipefile.write("\n")
      recipefile.write(numing)
      recipefile.write("\n")
      recipefile.write(orignumpep)
      recipefile.write("\n")
      recipefile.write(ingredient)
      recipefile.write("\n")
      recipefile.write(quantity)
      recipefile.write("\n")
      recipefile.write(units)
      recipefile.close()

    elif option == 2:
        recipefile = open("Recipe.txt")
        lines = recipefile.readlines()
        name = lines[0]
        numing = lines[1]
        numing = int(numing)
        orignumpep = lines[2]
        orignumpep = int(orignumpep)

        ingredients = lines[3].replace("/n", "").replace("[", "").replace("]","").replace("'", "").replace(",", "")
        quantitys = lines[4].replace("/n", "").replace("[", "").replace("]","").replace("'", "").replace(",", "")
        unitss = lines[5].replace("/n", "").replace("[", "").replace("]","").replace("'", "").replace(",", "")

        ingredient=[]
        quantity=[]
        units=[]

        ingredient = ingredients.split()
        quantity = quantitys.split()
        units = unitss.split()


        for x in range (0,numing):
             quantity[x] = int(quantity[x])

        numberpep = input("How many people is the meal for?")
        numberpep = int(numberpep)

        print("New Ingredients are as follows...")

        for x in range (0,numing):
            print(ingredient[x], " ", quantity[x]/orignumpep*numberpep, units[x])

input()

Many thanks!

sw123456
  • 3,339
  • 1
  • 24
  • 42
  • 4
    This question appears to be off-topic because it is about improving code, not solving problems. It could be asked at codereview.stackexchange.com though. – Steinar Lima Apr 19 '14 at 12:27
  • @SteinarLima: I disagree. Although this question refers to specific code, the question asked is quite general. The best home for this question is Stack Overflow. – Steven Rumbalski Apr 19 '14 at 12:42
  • Save a couple lines by using `int(input())` instead of adding an extra line to do so. – Quintec Apr 19 '14 at 15:09

2 Answers2

5

You could use a serialisation format; Python offers several.

For a list or dictionary containing string information, I'd use JSON, via the json module, as it is a format reasonably readable:

import json

# writing
with open("Recipe.txt","w") as recipefile:
    json.dump({
        'name': name, 'numing': numing, 'orignumpep': orignumpep,
        'ingredient': ingredient, 'quantity': quantity, 'units': units},
        recipefile, sort_keys=True, indent=4, separators=(',', ': '))

# reading
with open("Recipe.txt") as recipefile:
    recipedata = json.load(recipefile)

# optional, but your code requires it right now
name = recipedata['name']
numing = recipedata['numing']
orignumpep = recipedata['orignumpep']
ingredient = recipedata['ingredient']
quantity = recipedata['quantity']
units = recipedata['units']

The json.dump() configuration will produce very readable data, and most of all, you don't have to convert anything back to integers or lists; that is all preserved for you.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

As already mentioned, you could serialize your data using json, and I want to mention pickle module for serialization. You could use pickle module to store you entire data like this:

import pickle
with open("Recipe.txt", "wb") as fo:
    pickle.dump((ingredient, quantity, units), fo)

And load data:

with open("Recipe.txt", "rb") as fo:
    ingredient, quantity, units = pickle.load(fo)
psl
  • 906
  • 6
  • 6