Skip to content Skip to sidebar Skip to footer

Writing And Reading Lists To Text Files In Python: Is There A More Efficient Way?

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 chos

Solution 1:

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

# writingwithopen("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=(',', ': '))

# readingwithopen("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.

Solution 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
withopen("Recipe.txt", "wb") as fo:
    pickle.dump((ingredient, quantity, units), fo)

And load data:

withopen("Recipe.txt", "rb") as fo:
    ingredient, quantity, units = pickle.load(fo)

Post a Comment for "Writing And Reading Lists To Text Files In Python: Is There A More Efficient Way?"