Anton Bystrov
Anton Bystrov

Reputation: 134

os.path.exists is not working for particular directory

For example

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

os.path.exists doesn't work for this particular directory. Why? What should I do?

Upvotes: 2

Views: 1499

Answers (2)

falsetru
falsetru

Reputation: 369074

'\r' represents Carriage Return. To use \ as a backslash literally, you need to escape it:

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

or use raw string literal:

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

Upvotes: 4

Mureinik
Mureinik

Reputation: 311348

\r is the carriage-return character. You need to escape it either by doubling the \:

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

or use a raw string by prefixing it with an r:

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

Upvotes: 3

Related Questions