首页 > 解决方案 > 带有转义字符错误的 Python Windows 路径

问题描述

我有一个存储在名为“a”的变量中的 Windows 路径。当我尝试在代码中打印或使用它时,以某种方式将一些特殊字符添加到字符串中。

    >>> import re
    >>> from pathlib import Path 
    >>> 
    >>> 
    >>> a = "E:\POC\testing\functionalities\logs\timer.logs"
    >>> a
    'E:\\POC\testing\x0cunctionalities\\logs\timer.logs'
    >>>
    >>> Path(a)
    WindowsPath('E:/POC\testing\x0cunctionalities/logs\timer.logs')
    >>> Path.absolute(a)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "c:\program files (x86)\python38-32\lib\pathlib.py", line 1159, in absolute
        if self._closed:
    AttributeError: 'str' object has no attribute '_closed'
    >>>                 
    >>> re.escape(a)
    'E:\\\\POC\\\testing\\\x0cunctionalities\\\\logs\\\timer\\.logs'
    >>>
    >>> a.replace("\\", "/")
    'E:/POC\testing\x0cunctionalities/logs\timer.logs'
    >>> a.__repr__()
    "'E:\\\\POC\\testing\\x0cunctionalities\\\\logs\\timer.logs'"
    >>>

我能够处理所有特殊字符,但\f 以某种方式更改为 \x0c

一种解决方案是将r添加到字符串中,但我的路径存储在变量中。我怎样才能做到这一点?我正在使用 python 3.8.5 和 Windows 10

    >>> a = r"E:\POC\testing\functionalities\logs\timer.logs" 
    >>> a
    'E:\\POC\\testing\\functionalities\\logs\\timer.logs'
    >>>  
    >>> 
    >>> a = "E:\POC\testing\functionalities\logs\timer.logs"  
    >>> a = r"" + a
    >>> a
    'E:\\POC\testing\x0cunctionalities\\logs\timer.logs'
    >>>

标签: python-3.xwindowspathescaping

解决方案


根据您在@user8086906 帖子下的评论,您就不能这样做吗

a.replace('\\', '\')

? 我看到您在上面尝试过a.replace("\\", "/")-您能解释一下期望的行为是什么吗?在我的机器上,我发布的第一个片段有效。

编辑:

谢谢@Gopirengaraj C - 我明白了现在的问题。问题在于它\f是 Unicode 中的转义字符——更具体地说,它被称为“换页符”。我认为解决这个问题的一个好方法是避免replace并做这样的事情:

a = r'{0}'.format(a)

Lmk 如果可行的话。


推荐阅读