【问题标题】:os.path.exists is not working for particular directoryos.path.exists 不适用于特定目录
【发布时间】:2017-01-16 16:00:26
【问题描述】:

例如

 import os
filename = "C:\Windows\redir.txt"
if os.path.exists(filename):
    print ("Y")
else:
    print ("N")

os.path.exists 不适用于此特定目录。为什么?我该怎么办?

【问题讨论】:

    标签: python windows python-3.x os.path


    【解决方案1】:

    '\r' 代表回车。要将\ 用作反斜杠,您需要对其进行转义:

    filename = "C:\\Windows\\redir.txt"  # escape `\` s
    

    或使用原始字符串文字:

    filename = r"C:\Windows\redir.txt"  # raw string literal
    

    【讨论】:

      【解决方案2】:

      \r 是回车符。您需要通过加倍 \ 来逃避它:

      filename = "C:\Windows\\redir.txt"
      # Here ----------------^
      

      或通过在其前面加上 r 前缀来使用原始字符串:

      filename = r"C:\Windows\redir.txt"
      # Here ----^
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-16
        • 1970-01-01
        • 1970-01-01
        • 2023-02-08
        • 2016-09-20
        • 1970-01-01
        • 2012-12-19
        • 2017-11-08
        相关资源
        最近更新 更多