Skip to content Skip to sidebar Skip to footer

Python: Read Multiple Lines From A File And Make Instances Stored In An Dictionary

My struggle: Reading two lines and jumping over the third. Then I want to store all the objects in a dictionary with the name as keys. **** Ingredients.txt **** Name1 ingredient1/i

Solution 1:

Try something like this.

with open(file, 'r') as indata:
    lines = indata.readlines()
menu = dict()
for i in xrange(0, len(lines), 3):
    name = lines[i].rstrip('\n')
    ingredients = lines[i+1].rstrip('\n').split('/')
    f = Foodset(name)
    f.setIngredients(ingredients)
    menu[name] = f

For python 3.x use range instead of xrange.

Solution 2:

You can read three lines at once using itertools.islice

import itertools
withopen('ingredients.txt') as f:
    whileTrue:
        next_three_lines = list(itertools.islice(f, 3))
        ifnot next_three_lines:
            breakelse:
            print next_three_lines

In your case this will print

['Name1\n', 'ingredient1/ingredient2/ingredient3\n', '\n']['Name2\n', 'ingredient1/ingredient2\n', '\n']['Name3\n', '...']

Then you can change the print line to rstrip('\n') and use the first two elements of each next_three_lines to build your object:

tempString = str(next_three_lines[0].rstrip('\n'))
menu[tempString] = Foodset(tempString)
menu[tempString].setIngredients(next_three_lines[1].rstrip('\n').split('/')

Solution 3:

Since this is not a code writing service, I will show you a way to parse your file. Building a dictionary from the dishes and their ingredients is the simple part, so I will leave that to you.

Demo file input.txt:

Name1
ingredient1/ingredient2/ingredient3

Name2
ingredient1/ingredient2

Name3
ingredient1/ingredient2/ingredient3

Code:

from itertools import izip_longest

withopen('input.txt') as infile:
    for name, ingr, _ in izip_longest(*[infile]*3, fillvalue='\n'):
        ingredients = ingr.split('/')
        print name.strip()
        for ing in ingredients:
            print ing.strip()
        print

Output:

Name1
ingredient1
ingredient2
ingredient3

Name2
ingredient1
ingredient2

Name3
ingredient1
ingredient2
ingredient3

Explanation:

infile is an iterator, which is passed three times to izip_longest, so each iteration izip_longest will call next on the same iterator three times. I use an empty line as the fillvalue argument in case your file does not end with an empty line.

Splitting the string with the ingredients by the '/' character will give you a list of ingredients.

There's more explanation/information and also some alternatives on how to read multiple lines from a file at once here.

Post a Comment for "Python: Read Multiple Lines From A File And Make Instances Stored In An Dictionary"