2024-09-30 06:12:17 发布
网友
我尝试用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”
您可能希望将整个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())
这在您的案例中并不十分重要,但它是公认的最佳实践,应尽可能遵循
您可能希望将整个filo读入案例中的变量
见https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
我还提供了一些未经请求的建议:我建议使用所谓的上下文管理器,它会在您使用完文件后自动关闭该文件(即使由于某种原因读取文件失败)
这在您的案例中并不十分重要,但它是公认的最佳实践,应尽可能遵循
相关问题 更多 >
编程相关推荐