首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在python中打印文本文件中的所有行?

如何在python中打印文本文件中的所有行?
EN

Stack Overflow用户
提问于 2018-08-30 03:34:46
回答 1查看 37关注 0票数 0

我使用的文本文件有4行,但根据用户的不同,它可能更少也可能更多。

我的代码:

代码语言:javascript
复制
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']))

因此,输入将是(在我的例子中):

代码语言:javascript
复制
loadrecipefile("recipe_file.txt")

printrecipes()

然后,它将打印文本文件的每一行,我希望它看起来像这样:

代码语言:javascript
复制
Recipe1 1 4 3

Recipe2 0 2 4

Recipe3 3 0 1

Recipe4 2 1 0

但我只得到了最后一行:Recipe4 2 1 0

EN

回答 1

Stack Overflow用户

发布于 2018-08-30 03:55:19

您将在每个循环中覆盖cookbook变量的内容:

代码语言:javascript
复制
cookbook={wordList[0]:r1}

这将执行N次,每次都会创建一个包含一个键/值的新字典。

相反,您应该在each循环中添加到现有字典:

代码语言:javascript
复制
cookbook = {}

for ...:
    cookbook[wordList[0]] = r1

现在,你没有问到的部分,但你应该修复它,因为它看起来很糟糕:不要使用全局变量。什么时候?如果你从来不用它们,你就不会错。

不是将结果存储在全局变量中,而是从函数返回结果:

代码语言:javascript
复制
def loadrecipefile(recipe_file):

    ...

    return cookbook

然后,在另一个函数中,获取结果:

代码语言:javascript
复制
    def printrecipes(recipefile):
        cookbook = loadrecipefile(recipefile)
        for name, ingred in cookbook.items():
            ...

或者执行以下操作:

代码语言:javascript
复制
    def printrecipes(cookbook):
        for name, ingred in cookbook.items():
            ...

然后:

代码语言:javascript
复制
cookbook = loadrecipefile(recipe_file)
printrecipes(cookbook)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52084894

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档