I am trying to check if a particular directory path exists or not.
below is my code
temp_path = '\\diwali\NSID-HYD-01\college'
meta_path = os.path.realpath(temp_path)
print(os.path.exists(meta_path))
When I am trying to execute this, it is throwing error as below
temp_path = '\\diwali\NSID-HYD-01\college'
# ^
error
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 8-9: malformed \N character escape
Help me resolve this.
Python interprets backslashes ( \\
) inside strings as leading characters for escape codes. For example \\n
is a line-feed character.
If you want it to treat them as simply backslashes, add an r
before the string, like so:
temp_path = r'\\diwali\NSID-HYD-01\college'
another method is using two backslashes \\\\
before N
like this:
temp_path = '\\diwali\\NSID-HYD-01\college'
If you are get it from UI (as you mentioned in comments) you can replace \\
with \\\\
:
temp_path = '\\diwali\NSID-HYD-01\college'.replace("\\", "\\\\")
# '\\diwali\\NSID-HYD-01\\college'
You best bet would be escaping all backslashes:
path_string.replace('\\\\', '\\\\\\\\')
This will replace single backslash with two backslashes (Since a single \\ would escape the quote you have to escape thats why its two and four backslashes)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.