【问题标题】:Printing out a text file (Python)打印出一个文本文件(Python)
【发布时间】:2018-03-24 19:33:13
【问题描述】:

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

当存在 '\n' 时,它不会实际创建新行,而是打印 '\n'。

['\n', '用户名:\n', 'Tes123\n', '学科:\n', '计算机科学\n', '难度:\n','困难\n','分数:\n','5\n','等级:\n','A\n']

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

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

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

【问题讨论】:

  • data 是一个列表。当您打印时,它将打印整个列表
  • 你可以这样想:当你打印data时,你试图将它的值显示为一个字符串。在您的情况下,该值是 string 元素的集合。每个字符串都包含\n 字符。如果您希望将\n 字符作为转义序列读取并导致换行,则必须将字符串本身作为参数传递给打印函数。

标签: python python-3.x file formatting output


【解决方案1】:

这是一种从文件中读取数据并创建新行的简单有效的方法。

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

这会在每次到达句子或行的末尾时将数据读入新行。有关更多信息,请参阅Input / Output for python。

【讨论】:

  • 非常感谢。
【解决方案2】:

你可能想试试这个:

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

附言 最好不要将 \n 保存在文件中,而是这样做:

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】:

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

    这个怎么样?

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

    【讨论】:

      【解决方案4】:

      你可以在你的打印方法之后尝试这些

      for line in data:
          print(line, end='')
      print('-'*10)
      print(''.join(data))
      

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-06
          • 2023-03-15
          • 1970-01-01
          • 2020-11-12
          • 2022-01-23
          相关资源
          最近更新 更多