Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Convert Windows File path in a variable

Given is a variable that contains a windows file path. I have to then go and read this file. The problem here is that the path contains escape characters, and I can't seem to get rid of it. I checked os.path and pathlib, but all expect the correct text formatting already, which I can't seem to construct.

For example this. Please note that fPath is given, so I cant prefix it with r for a rawpath.

#this is given, I cant rawpath it with r 
fPath = "P:\python\t\temp.txt"

file = open(fPath, "r")
for line in file:
    print (line)

How can I turn fPath via some function or method from:

"P:\python\t\temp.txt"

to

"P:/python/t/temp.txt"

I've tried also tried .replace("\","/"), which doesnt work.

I'm using Python 3.7 for this.

like image 340
RedBoxes Avatar asked Aug 25 '26 15:08

RedBoxes


1 Answers

You can use os.path.abspath() to convert it:

print(os.path.abspath("P:\python\t\temp.txt"))

>>> P:/python/t/temp.txt

See the documentation of os.path here.

like image 79
Nordle Avatar answered Aug 27 '26 06:08

Nordle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!