我正在尝试以某种格式从文本文件中打印每行文本,但它只打印最后一行而不是所有行。我正在使用的文本文件有4行,但根据用户可能有更少或更多。
我的代码:def loadrecipefile (recipe_file):
infile=open(recipe_file)
Linelist=infile.readlines()
global cookbook
for line in Linelist:
wordList=line.split()
r1={'apple':int(wordList[1]),'beets':int(wordList[2]),'carrots':int(wordList[3])}
cookbook={wordList[0]:r1}
def printrecipes():
for name,ingred in cookbook.items():
print(name + " " + str(ingred['apple']) + " " + str(ingred['beets']) + " " + str(ingred['carrots']))
所以输入将是(在我的情况下):loadrecipefile("recipe_file.txt")
printrecipes()
那么它会打印我希望它看起来像文本文件的每一行:Recipe1 1 4 3
Recipe2 0 2 4
Recipe3 3 0 1
Recipe4 2 1 0
但我只得到最后一行: Recipe4 2 1 0
我不知道如何解决这个问题,因为loadrecipe文件似乎工作得很好jsut printcipes没有打印出我想要的东西