繁体   English   中英

无法在Windows中运行的Python中从其他目录打开文件

[英]Unable to open a file from different directory in Python running in Windows

我无法打开目录中的文件。

请参见下面的代码:

file = open("E:\Python_Scratch\test.txt","w")

但是打开文件时出现以下错误。

   E:\Python_Scratch
     ^
SyntaxError: invalid syntax

您能帮我打开文件吗?

在Python中,字符串内的反斜杠用于给出诸如换行符( \\n )之类的命令。

因此,如果要编写反斜杠而不是给出命令,请使用两个反斜杠:

file = open("E:\\\\Python_Scratch\\\\test.txt","w")

您可以查阅文档以获取更多信息。

似乎您使用的是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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM