简体   繁体   English

打印出文本文件(Python)

[英]Printing out a text file (Python)

I am making a Quiz. 我在做测验。 When I try to print the results which are stored in a file, this is the output: 当我尝试打印存储在文件中的结果时,这是输出:

Instead of actually creating new lines when there is a '\\n' it prints the '\\n' instead. 当出现'\\ n'时,它不会实际创建新行,而是打印'\\ n'。

['\\n', 'Username:\\n', 'Tes123\\n', 'Subject:\\n', 'Computer Science\\n', 'Difficulty:\\n', 'Hard\\n', 'Score:\\n', '5\\n', 'Grade:\\n', 'A\\n'] ['\\ n','用户名:\\ n','Tes123 \\ n','主题:\\ n','计算机科学\\ n','难度:\\ n','困难\\ n','评分:\\ n','5 \\ n','等级:\\ n','A \\ n']

In the text file the results are presented like this. 在文本文件中,结果显示如下。 This is what I want the output to look like: 这就是我想要的输出看起来像:

在此处输入图片说明

This is my code to read the data from this text file and then print it into the interpreter. 这是我的代码,用于从此文本文件中读取数据,然后将其打印到解释器中。

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

Here is a simple and efficient way to read data in from a file and creating a new lines. 这是一种从文件中读取数据并创建新行的简单有效的方法。

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

This reads the data into new lines every time it reaches the end of the sentence or line. 每次到达句子或行末时,这会将数据读入新行。 For more information see Input / Output for python. 有关更多信息,请参见python的输入/输出

You might want to try this instead: 您可能想尝试以下方法:

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

ps it might be better for you not to save \\n in the file at all and just do this: ps最好不要完全将\\ 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))

You basically have to iter on your data. 基本上,您必须遍历数据。

How about this? 这个怎么样?

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

you can try these after your print method 您可以在打印方法后尝试这些

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

Another way of '\\n' is os.linesep . '\\ n'的另一种方式是os.linesep This page helped me with printing the file if that is what you need. 如果需要, 此页面可帮助我打印文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM