Kotauskas
Kotauskas

Reputation: 1374

Python: os.path.realpath() - how to fix unescaped backslashes?

I want to get the path to the currently executed script.I have used
os.path.realpath(__file__), however, it returns a string like D:\My Stuff\Python\my_script.py without proper backslash escaping! How to escape them?

Upvotes: 3

Views: 1623

Answers (2)

DeeBee
DeeBee

Reputation: 319

Depending on your use case, you may appreciate the built-in repr function to get a "printable representation of an object" https://docs.python.org/2/library/functions.html#func-repr

path = 'D:\My Stuff\Python\my_script.py'
print(path)
D:\My Stuff\Python\my_script.py
print(repr(path))
'D:\\My Stuff\\Python\\my_script.py'

Upvotes: 0

eli-bd
eli-bd

Reputation: 1634

path = "D:\My Stuff\Python\my_script.py"
escaped_path = path.replace("\\", "\\\\")
print(escaped_path)

Will output

D:\\My Stuff\\Python\\my_script.py

Upvotes: 3

Related Questions