[英]How to print a text file in python
I'm fairly new to coding and am having some issues printing a text file. 我是编码新手,在打印文本文件时遇到一些问题。
Here's my file: 这是我的档案:
Player1: 1
Player2: 3
Here's my code: 这是我的代码:
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
At the moment its just printing whitespace. 目前,它只是打印空白。
I'm probably missing something obvious or have gone down the wrong road altogether, so any help would be appreciated. 我可能缺少明显的东西,或者完全走错了路,所以我们将不胜感激。
Thanks in advance. 提前致谢。
Just use the below code sample to print the whole file. 只需使用以下代码示例即可打印整个文件。
try:
with open("scoreTable.txt", "r" ) as scoreTable:
file_content = scoreTable.read()
print str(file_content)
except FileNotFoundError as e:
print e.message
You are performing read
operation on scoreTable.txt
twice, which is not required. 您对
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
While we are on this subject use with
statement to read files(so you wont have to keep track to close the file) 当我们在此主题上时,使用
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.