Skip to content
Advertisement

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:pythonttemp.txt"

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

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

"P:pythonttemp.txt"

to

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

I’ve tried also tried .replace(“”,”/”), which doesnt work.

I’m using Python 3.7 for this.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement