Writing and reading lists to text files in Python: Is there a more efficient way?
Question: 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!


Answer: 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](https://docs.python.org/2/library/json.html), 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.

