如何在python中打印textfile中的所有行?
我试图以某种格式打印文本文件中的每一行文本,但它只打印最后一行,而不是所有行。 我正在使用的文本文件有4行,但根据用户的不同,可能会有更少或更多的行 我的代码:如何在python中打印textfile中的所有行?,python,Python,我试图以某种格式打印文本文件中的每一行文本,但它只打印最后一行,而不是所有行。 我正在使用的文本文件有4行,但根据用户的不同,可能会有更少或更多的行 我的代码: def loadrecipefile (recipe_file): infile=open(recipe_file) Linelist=infile.readlines() global cookbook for line in Linelist: wordList=line.split(
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']))
因此,输入将是(在我的情况下):
然后它会打印文本文件的每一行,我希望它看起来像:
Recipe1 1 4 3
Recipe2 0 2 4
Recipe3 3 0 1
Recipe4 2 1 0
但我只得到最后一行:Recipe4 2 1 0
我不知道该怎么做,因为loadrecipefile似乎工作得很好,但printrecipes没有打印我想要的内容您正在覆盖每个循环中
cookbook
变量的内容:
cookbook={wordList[0]:r1}
cookbook = {}
for ...:
cookbook[wordList[0]] = r1
执行N次,每次创建一个包含一个键/值的新字典
您应该在每个循环中向现有字典添加:
cookbook={wordList[0]:r1}
cookbook = {}
for ...:
cookbook[wordList[0]] = r1
现在,您没有问的部分,但您应该修复,因为它看起来很糟糕:不要使用全局变量。什么时候如果你从不使用它们,你就不会错 从函数返回结果,而不是将结果存储在全局变量中:
def loadrecipefile(recipe_file):
...
return cookbook
然后,在另一个函数中,取结果:
def printrecipes(recipefile):
cookbook = loadrecipefile(recipefile)
for name, ingred in cookbook.items():
...
或者这样做:
def printrecipes(cookbook):
for name, ingred in cookbook.items():
...
然后:
cookbook = loadrecipefile(recipe_file)
printrecipes(cookbook)
但是我试过这样做,它说对于printrecipes(),recipefile没有定义,那么我如何在printrecipes中使用loadrecipefile?@TaitmiLee在这种情况下,
printrecipes
也必须将recipefile
作为参数。我修改了答案。@TaitmiLee下一步是创建一个Cookbok
类,方法是load\u from\u file
和print\u recipes
,这两种方法都使用cookbook
中当前数据的成员变量。