繁体   English   中英

如何在python中打印文本文件

[英]How to print a text file in python

我是编码新手,在打印文本文件时遇到一些问题。
这是我的档案:

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

目前,它只是打印空白。
我可能缺少明显的东西,或者完全走错了路,所以我们将不胜感激。
提前致谢。

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

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

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

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

暂无
暂无

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

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