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

I want to get the path of the currently executing script. I have used os.path.realpath(__file__)

, however, it returns a string of type D:\My Stuff\Python\my_script.py

without the proper backslash! How can you avoid them?

+3


source to share


2 answers


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

      

Will output



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

      

+3


source


Depending on your use case, you can evaluate the built-in function repr

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'

      

0


source







All Articles