无法在 VS 代码中读取文本文件 (Python)

Can't read text file in VS code (Python)

所以我在 VS Code 中有这个 Python 代码:

s = open("name.txt")
print("Your name is", s)

我的文本文件“name.txt”与我的程序 运行 在同一文件夹中。此文本文件仅包含文本“Johnny”。

当运行文件时,我首先得到错误信息:

FileNotFoundError: [Errno 2] No such file or directory: 'name.txt'

但经过一番谷歌搜索后,我打开了设置“在文件目录中执行”:

但是现在,我得到了这个无意义的输出:

Your name is <_io.TextIOWrapper name='name.txt' mode='r' encoding='cp1252'>

但应该是:

Your name is Johnny

有人知道哪里出了问题吗?

你需要读取文件,此时你输出到s变量的是一个对象。要将文件读出为字符串,您需要包含的是:

s = open("name.txt", "r").read() 要么 s = open("name.txt", "r").readlines()

"r" 指的是您只是在读取文件,这通常是隐含的,但最好包含它以提高可读性)

您必须将读取函数分配给变量而不是打开 s = read(name.txt)