【问题标题】:Python Windows path with escape character error带有转义字符错误的 Python Windows 路径
【发布时间】:2021-07-23 10:16:53
【问题描述】:

我有一个存储在名为“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.x windows path escaping


    【解决方案1】:

    使用原始字符串或转义反斜杠:

    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”实现上述相同的结果
    【解决方案2】:

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

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

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

    编辑:

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

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

    Lmk 如果可行的话。

    【讨论】:

    • 'E:/POC\testing\x0cunctionalities/logs\timer.logs' in this value of f in functionalities 更改为 \x0c
    猜你喜欢
    • 2015-09-12
    • 2012-03-16
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    相关资源
    最近更新 更多