为什么python读取文件中的信息而不读取其内容?

2024-09-30 06:12:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试用Python读取并打印文件score.txt中的文本(score.txt中是文本hrllo world),我编写了以下命令:

score = open("data/score.txt", "r")
print(score)

输出为:

<_io.TextIOWrapper name='data/score.txt' mode='r' encoding='cp1250'>

如何从score.txt文件打印“hello world”


Tags: nameio文本命令txtworlddatamode
1条回答
网友
1楼 · 发布于 2024-09-30 06:12:17

您可能希望将整个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())

这在您的案例中并不十分重要,但它是公认的最佳实践,应尽可能遵循

相关问题 更多 >

    热门问题