为什么我的文件路径中出现 Unicode 转义的 SyntaxError?

新手上路,请多包涵

我要访问的文件夹名为 python,在我的桌面上。

当我尝试访问它时出现以下错误

>>> os.chdir('C:\Users\expoperialed\Desktop\Python')
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

原文由 inspired 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 400
1 个回答

您需要使用 原始 字符串、双斜线或使用正斜线:

 r'C:\Users\expoperialed\Desktop\Python'
'C:\\Users\\expoperialed\\Desktop\\Python'
'C:/Users/expoperialed/Desktop/Python'

在常规 Python 字符串中, \U 字符组合表示扩展的 Unicode 代码点转义。

对于任何其他已 识别的转义序列,您可以遇到任意数量的其他问题,例如 \a\t\x

请注意,从 Python 3.6 开始,无法识别的转义序列会触发 DeprecationWarning (您必须删除这些的默认过滤器),并且在未来的 Python 版本中,此类无法识别的转义序列将导致 SyntaxError 。目前没有设置具体的版本,但是Python会先在版本中使用 SyntaxWarning ,然后才会报错。

如果您想在 Python 3.6 及更高版本中查找此类问题,可以使用警告过滤器将警告转换为 SyntaxError 异常 --- error:^invalid escape sequence .*: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'

原文由 Martijn Pieters 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题