【问题标题】:How do I print a .txt file line-by-line? [duplicate]如何逐行打印 .txt 文件? [复制]
【发布时间】:2022-11-24 02:43:15
【问题描述】:

我正在制作我的第一个游戏并想在 .txt 文件中创建一个计分板,但是当我尝试打印计分板时它不起作用。

with open("Scores.txt", "r") as scores:
        for i in range(len(score.readlines())):
          print(score.readlines(i + 1))

它没有像我预期的那样打印 .txt 文件的每一行,而是只打印 []

.txt 文件的内容是:

姓名: 年龄: 性别: 分数:

我知道它只有一根线,但它应该仍然可以工作,不是吗?

*请注意,.txt 文件中的每个单词之间都有空格,但 Stack Overflow 格式不允许我显示该空格。

【问题讨论】:

    标签: python txt


    【解决方案1】:

    score.readlines() 的结果分配给一个变量。然后你可以遍历它并对其进行索引。

    with open("Scores.txt", "r") as scores:
        scorelines = scores.readlines()
    
    for line in scorelines:
        print(line)
    

    【讨论】:

      【解决方案2】:

      .readlines() 读取所有内容,直到到达文件末尾。重复调用它会返回[],因为文件搜索器已经在末尾。

      尝试像这样遍历文件:

      with open("Scores.txt", "r") as scores:
          for line in scores:
              print(line)
      

      【讨论】:

        猜你喜欢
        • 2013-08-15
        • 2016-05-13
        • 2012-09-05
        • 2022-12-17
        • 1970-01-01
        • 2014-04-02
        • 1970-01-01
        • 2012-02-18
        • 2017-08-29
        相关资源
        最近更新 更多