我无法打开位于目录中的文件。无法在Windows中运行的Python中的不同目录中打开文件
请参阅下面的代码:
file = open("E:\Python_Scratch\test.txt","w")
,但我收到以下错误,而打开该文件。
E:\Python_Scratch
^
SyntaxError: invalid syntax
您可以帮我解决如何打开文件吗?
我无法打开位于目录中的文件。无法在Windows中运行的Python中的不同目录中打开文件
请参阅下面的代码:
file = open("E:\Python_Scratch\test.txt","w")
,但我收到以下错误,而打开该文件。
E:\Python_Scratch
^
SyntaxError: invalid syntax
您可以帮我解决如何打开文件吗?
在Python中,字符串内的反斜杠用于提供诸如换行符(\n
)之类的命令。
所以,如果你想要写一个反斜杠,而不是给一个命令,使用两个反斜杠:
file = open("E:\\Python_Scratch\\test.txt","w")
可以为有关它的更多情报咨询Documentation。
看来你是在Windows操作系统中,尝试这种格式
file = open(r"E:\\Python_Scratch\test.txt","w")
#raw path(string) by r before ''
#after drive name :\\ double slash, you will be fine if you use single or double slashes after next path(one dir deep) and on-wards.
忘记在上一行括号给你的错误在Python 2.x版本例如:
x = (
print("E:\Python_Scratch\test.txt")
输出:
File "test.py", line 2
print("E:\Python_Scratch\test.txt")
^
SyntaxError: invalid syntax
另外,与Python字符串,单反斜杠可以被解释为转义码。在你的情况下,\t
是一个标签:
>>> print("E:\Python_Scratch\test.txt")
E:\Python_Scratch est.txt
取而代之。使用双反斜线来表示你想要的字符串中一个真正的反斜杠,或使用原始字符串(注意领导r
):
>>> print(r"E:\Python_Scratch\test.txt")
E:\Python_Scratch\test.txt
>>> print("E:\\Python_Scratch\\test.txt")
E:\Python_Scratch\test.txt
可以张贴整个代码?该行没有无效的语法 –