我要访问的文件夹名为 python,位于我的桌面上。
当我尝试访问它时收到以下错误
>>> os.chdir('C:\Users\expoperialed\Desktop\Python')
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
最佳答案
您需要使用 raw 字符串、双斜杠或使用正斜杠:
r'C:\Users\expoperialed\Desktop\Python'
'C:\\Users\\expoperialed\\Desktop\\Python'
'C:/Users/expoperialed/Desktop/Python'
在常规 Python 字符串中,\U
字符组合表示扩展的 Unicode 代码点转义。
您可以遇到任意数量的其他问题,对于任何其他 recognised escape sequences ,例如 \a
、\t
或 \x
。
请注意,从 Python 3.6 开始,无法识别的转义序列可能会触发 DeprecationWarning
(您必须删除这些默认过滤器),并且在 Python 的 future 版本中,此类无法识别的转义序列将导致 SyntaxError
。目前没有设置具体的版本,但是Python会先在版本中使用SyntaxWarning
才会报错。
如果您想在 Python 3.6 及更高版本中发现此类问题,可以使用警告过滤器 error:^invalid 转义序列将警告转换为
(通过 command line switch、environment variable 或 function call):SyntaxError
异常。* :DeprecationWarning
Python 3.10.0 (default, Oct 15 2021, 22:25:32) [Clang 13.0.0 (clang-1300.0.29.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import warnings
>>> '\expoperialed'
'\\expoperialed'
>>> warnings.filterwarnings('default', '^invalid escape sequence .*', DeprecationWarning)
>>> '\expoperialed'
<stdin>:1: DeprecationWarning: invalid escape sequence '\e'
'\\expoperialed'
>>> warnings.filterwarnings('error', '^invalid escape sequence .*', DeprecationWarning)
>>> '\expoperialed'
File "<stdin>", line 1
'\expoperialed'
^^^^^^^^^^^^^^^
SyntaxError: invalid escape sequence '\e'
关于python - 为什么我的文件路径中出现 Unicode 转义的 SyntaxError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18084554/