【问题标题】:python - backward slash is removed while referring to path in network on windowspython - 在Windows上引用网络中的路径时删除了反斜杠
【发布时间】:2021-01-13 12:43:13
【问题描述】:
netowrk_path = '\\shared_storage\test.txt'
cmd = f'/c copy {netowrk_path} D:\\temp'
print(cmd)

这会在复制时打印并给出错误

/c copy \shared_storage test.txt D:\temp

但它实际上应该打印

/c copy \\shared_storage test.txt D:\temp

【问题讨论】:

  • 反斜杠在 Python 字符串文字中被特别解释,在字符串前面加上“r”,如 e。 G。 r'\\shared_storage'.

标签: python windows cmd


【解决方案1】:

反斜杠(\)是一种转义某些字符learn more的方法

您可以将字符串定义为原始字符串

string = r'\\somenetworkpath'
print(string)

输出: \\somenetworkpath

read more about the raw string

【讨论】:

    【解决方案2】:

    您可以通过以下方式使用repr

    print(repr(cmd))
    

    这将为您提供所需的输出

    您可以使用raw string并按以下方式格式化:

    netowrk_path = r'\\shared_storage\test.txt'
    cmd = rf'/c copy {netowrk_path} D:\\temp'
    print(cmd)
    

    【讨论】:

      【解决方案3】:

      您可以使用双斜杠 \\ 替换所有单个 \ 或使用 r 将其设为原始字符串,如上所示。

      【讨论】:

        猜你喜欢
        • 2015-10-16
        • 2023-03-22
        • 2020-11-25
        • 2013-01-22
        • 2014-04-29
        • 2014-02-04
        • 2019-08-06
        • 2012-08-30
        • 1970-01-01
        相关资源
        最近更新 更多