Python 为什么我的文件路径中出现 Unicode 转义的 SyntaxError?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18084554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why do I get a SyntaxError for a Unicode escape in my file path?
提问by inspired
The folder I want to get to is called python and is on my desktop.
我要访问的文件夹名为 python,在我的桌面上。
I get the following error when I try to get to it
当我尝试访问它时出现以下错误
>>> os.chdir('C:\Users\expoperialed\Desktop\Python')
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
回答by Martijn Pieters
You need to use a rawstring, double your slashes or use forward slashes instead:
您需要使用原始字符串、双斜杠或使用正斜杠:
r'C:\Users\expoperialed\Desktop\Python'
'C:\Users\expoperialed\Desktop\Python'
'C:/Users/expoperialed/Desktop/Python'
In regular python strings, the \U
character combination signals a extended Unicode codepoint escape.
在常规 python 字符串中,\U
字符组合表示扩展的 Unicode 代码点转义。
You can hit any number of other issues, for any of the recognised escape sequences, such as \a
or t
or \x
, etc.
对于任何已识别的转义序列,例如\a
ort
或\x
等,您可以遇到任意数量的其他问题。
回答by pope
C:\\Users\\expoperialed\\Desktop\\Python
This syntax worked for me.
C:\\Users\\expoperialed\\Desktop\\Python
这种语法对我有用。
回答by SPK
All the three syntax work very well.
所有这三种语法都非常有效。
Another way is to first write
另一种方式是先写
path = r'C:\user\...................' (whatever is the path for you)
path = r'C:\user\...................'(无论你的路径是什么)
and then passing it to os.chdir(path)
然后将其传递给 os.chdir(path)
回答by coder
This usually happens in Python 3. One of the common reasons would be that while specifying your file path you need "\\" instead of "\". As in:
这通常发生在 Python 3 中。常见的原因之一是在指定文件路径时需要“\\”而不是“\”。如:
filePath = "C:\User\Desktop\myFile"
For Python 2, just using "\" would work.
对于 Python 2,只需使用“\”即可。
回答by POOJA TAYADE
f = open('C:\Users\Pooja\Desktop\trolldata.csv')
Use '\\' for python program in Python version 3 and above.. Error will be resolved..
在 Python 版本 3 及更高版本中对 Python 程序使用 '\\' .. 错误将得到解决..
回答by Bec
I had the same error. Basically, I suspect that the path cannot start either with "U" or "User" after "C:\". I changed my directory to "c:\file_name.png" by putting the file that I want to access from python right under the 'c:\' path.
我有同样的错误。基本上,我怀疑路径不能在“C:\”之后以“U”或“User”开头。我将我想从 python 访问的文件放在“c:\”路径下,将我的目录更改为“c:\file_name.png”。
In your case, if you have to access the "python" folder, perhaps reinstall the python, and change the installation path to something like "c:\python". Otherwise, just avoid the "...\User..." in your path, and put your project under C:.
在您的情况下,如果您必须访问“python”文件夹,请重新安装python,并将安装路径更改为“c:\python”之类的内容。否则,只需避免路径中的“...\User...”,并将您的项目放在 C: 下。
回答by Pygirl
Use this
用这个
os.chdir('C:/Users\expoperialed\Desktop\Python')