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

标签 python windows filenames

我要访问的文件夹名为 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 转义序列将警告转换为 SyntaxError 异常。* :DeprecationWarning(通过 command line switchenvironment variablefunction call):

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/

相关文章:

c# - 如何使用c#获取特定文件名

Python 在特定目录模式中搜索文件名模式

python - Flask - 由于 functools.wraps,一条闪现消息不会消失?

c# - 当应用程序进程被终止/崩溃时终止子进程

windows - Inno Setup 在静默安装期间将锁定文件替换推迟到下一次重新启动

windows - 如何在 Windows 批处理文件中将 PATH 设置为另一个带空格的变量值

linux - 在 BASH 中使用特殊字符从文件名中批量删除子字符串

python - 在 Python 中解构字典和对象

python - Windows - Cygwin - Vim - Python - 导入错误

python - Numpy 将角度范围从 (-Pi, Pi) 转换为 (0, 2*Pi)