微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

带有转义字符错误的 Python Windows 路径

如何解决带有转义字符错误的 Python Windows 路径

我有一个 Windows 路径存储在一个名为“a”的变量中。当我尝试在代码中打印或使用它时,不知何故在字符串中添加了一些特殊字符。

    >>> 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'
    >>>

解决方法

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

a = r"E:\POC\testing\functionalities\logs\timer.logs"

a = "E:\\POC\\testing\\functionalities\\logs\\timer.logs"
,

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

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

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

编辑:

谢谢@Gopirengaraj C - 我知道现在是什么问题了。问题在于 \f 是 Unicode 中的转义字符 - 更具体地说,它被称为 “表单提要”。我认为解决这个问题的一个好方法是避免 replace 并执行以下操作:

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

Lmk 如果有效。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。