Python 3.x 如何在终端中使用python 3.7.1从我的桌面打开文本文件

Python 3.x 如何在终端中使用python 3.7.1从我的桌面打开文本文件,python-3.x,file,syntax-error,Python 3.x,File,Syntax Error,我把一个名为“test.txt”的文本文件保存到我的桌面上,文件中只写了我的名字,David。然后,我打开terminal并打开python 3.7.1,编写了以下代码,试图查看我的名字David的填充: open("/Users/David/Desktop/test.txt,"r") 但是,我收到以下错误消息: SyntaxError:扫描字符串文字时下线 有人知道如何避免这个错误,并让我的名字David从桌面上的test.txt文件中读取吗?还是我完全弄错了?文件路径后缺少引号。应该是这样

我把一个名为“test.txt”的文本文件保存到我的桌面上,文件中只写了我的名字,David。然后,我打开terminal并打开python 3.7.1,编写了以下代码,试图查看我的名字David的填充:

open("/Users/David/Desktop/test.txt,"r")
但是,我收到以下错误消息:

SyntaxError:扫描字符串文字时下线


有人知道如何避免这个错误,并让我的名字David从桌面上的test.txt文件中读取吗?还是我完全弄错了?

文件路径后缺少引号。应该是这样的:

open("/Users/David/Desktop/test.txt","r")
                                   ^ This quotation mark

这将正确打开文件,但您仍需要实际读取。

文件路径后缺少引号。应该是这样的:

open("/Users/David/Desktop/test.txt","r")
                                   ^ This quotation mark
myfile = open("/Users/David/Desktop/test.txt","r") #returns file handle
myfile.read() # reading from the file
myfile.close() # closing the file handle, to release the resources. 

这将正确打开文件,但是您仍然需要实际读取。

正如@Matt所解释的,您缺少引号

myfile = open("/Users/David/Desktop/test.txt","r") #returns file handle
myfile.read() # reading from the file
myfile.close() # closing the file handle, to release the resources. 
您可以按照下面的方法打开文件并从中读取

myfile = open("/Users/David/Desktop/test.txt","r") #returns file handle
myfile.read() # reading from the file
myfile.close() # closing the file handle, to release the resources. 

正如@Matt所解释的,您缺少引用

您可以按照下面的方法打开文件并从中读取

myfile = open("/Users/David/Desktop/test.txt","r") #returns file handle
myfile.read() # reading from the file
myfile.close() # closing the file handle, to release the resources. 

您缺少其他人提到的其他报价。尝试使用
with open
语句,因为它可以为您处理资源,这意味着您不需要指定
.close()


您缺少了其他人提到的其他报价。尝试使用
with open
语句,因为它可以为您处理资源,这意味着您不需要指定
.close()


您可以将
一起使用,当您从块中出来并放入目录链接时,它将自动关闭文件

with open(r"Directory_link", "r") as file1:
    FileContent = file1.read()
    print(FileContent)

您可以将
一起使用,当您从块中出来并放入目录链接时,它将自动关闭文件

with open(r"Directory_link", "r") as file1:
    FileContent = file1.read()
    print(FileContent)