簡體   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