python - 为什么python读取文件中的信息而不是它的内容?
问题描述
我尝试 Python 读取然后从文件 score.txt 打印文本(在 score.txt 中是文本 hrllo 世界)我写了这个命令:
score = open("data/score.txt", "r")
print(score)
输出是:
<_io.TextIOWrapper name='data/score.txt' mode='r' encoding='cp1250'>
如何从文件 score.txt 中打印“hello world”?
解决方案
在您的情况下,您可能希望将整个filo 读入变量中。
score = open("data/score.txt", "r").read()
请参阅https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
我还提供了一些不请自来的建议:我建议使用所谓的上下文管理器,它会在您使用完文件后自动关闭文件(即使由于某种原因读取文件失败)。
with open("data/score.txt", "r") as score_file:
print(score_file.read())
在您的情况下,这并不是很重要,但这是公认的最佳实践,应尽可能遵循。