Search code examples
pythonpython-3.x

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.


Solution

  • I've solved it.

    The issues lies with the python interpreter. \t and all the others don't exist as such data, but are interpretations of nonprint characters.

    So I got a bit lucky and someone else already faced the same problem and solved it with a hard brute-force method:

    http://code.activestate.com/recipes/65211/

    I just had to find it.

    After that I have a raw string without escaped characters, and just need to run the simple replace() on it to get a workable path.