如何在python中打印文本文件

时间:2016-04-05 09:14:10

标签: python file python-3.x

我对编码很新,并且在打印文本文件时遇到了一些问题 这是我的文件:

Player1: 1  
Player2: 3  

这是我的代码:

try:
    scoreTable = open("scoreTable.txt", "r")
    line = scoreTable.readlines()
    for i in range(0, (len(line))):
        print(scoreTable.read(len(line[i].strip("\n"))))
    scoreTable.close()
except FileNotFoundError:
    pass

目前只是打印空白。
我可能错过了一些显而易见的事情或完全走错了道路,所以任何帮助都会受到赞赏 提前致谢。

2 个答案:

答案 0 :(得分:0)

只需使用以下代码示例即可打印整个文件。

try:
    with open("scoreTable.txt", "r" ) as scoreTable:
        file_content = scoreTable.read()
        print str(file_content)
except FileNotFoundError as e:
    print e.message

答案 1 :(得分:0)

您正在read执行scoreTable.txt次操作两次,这不是必需的。

try:
    scoreTable = open("scoreTable.txt", "r")
    lines = scoreTable.readlines()
    #here in lines you have whole file stored so no need to try to read from files variable again
    for line in lines:
        print line
    scoreTable.close()
except FileNotFoundError:
    pass

虽然我们在这个主题上使用with语句来读取文件(所以你不必跟踪关闭文件)

with open("scoreTable.txt", "r" ) as f:
    lines = f.readlines()
    for line in lines:
        print line