代码之家  ›  专栏  ›  技术社区  ›  Jamie Wilson

打印文本文件(Python)

  •  1
  • Jamie Wilson  · 技术社区  · 7 年前

    我正在做测验。当我尝试打印存储在文件中的结果时,这是输出:

    当有“\n”时,它不会实际创建新行,而是打印“\n”。

    [“\n”,“用户名:\n”,“Tes123\n”,“主题:\n”,“计算机科学\n”, '难度:\n','Hard\n','Score:\n','5\n','Grade:\n','A\n']

    在文本文件中,结果如下所示。 这就是我希望输出的样子:

    enter image description here

    这是我从文本文件中读取数据,然后将其打印到解释器中的代码。

    with open(leaderboarddetails) as f:
        data = f.readlines()
        print("Here are all the current results:")
        print('\n')
        print(data)
    
    5 回复  |  直到 7 年前
        1
  •  0
  •   tlarsin    7 年前

    下面是一种从文件中读入数据并创建新行的简单而高效的方法。

    for line in f:
     print(line, end='')
    

    每当数据到达句子或行的末尾时,就会将其读入新行。有关更多信息,请参阅 Input / Output 对于python。

        2
  •  0
  •   Daniel Meltzer    7 年前

    您可能希望尝试以下操作:

    with open(leaderboarddetails) as f:
    data = f.readlines()
    print("Here are all the current results:")
    print('\n')
    for item in data:
        print(item)
    

    p、 s 最好不要保存在文件中,只需执行以下操作:

    with open(leaderboarddetails) as f:
    data = f.readlines()
    print("Here are all the current results:")
    print('\n')
    for item in data:
        print("\n"+str(item))
    
        3
  •  0
  •   Hannan    7 年前

    你基本上必须对你的数据进行迭代。

    这个怎么样?

    with open(leaderboarddetails) as f:
        data = f.readlines()
        print("Here are all the current results:")
        print('\n')
        for info in data:
            print(info)
    
        4
  •  0
  •   Hosam-Elnabawy    7 年前

    您可以在使用打印方法后尝试这些

    for line in data:
        print(line, end='')
    print('-'*10)
    print(''.join(data))
    
        5
  •  0
  •   geizio Mr. Alien    7 年前

    “\n”的另一种方式是 os.linesep This page 如果你需要的话,帮我打印文件。

    with open(leaderboarddetails,'r') as f:
        print(f.read())