0

I often use os.path.abspath(file) on a file address entered via the command line to sanitize it before I handle the file.

That means; performing the following:

outputPath = 'c:\Users\JEHOSHAPHAKSHAY\Desktop'
os.path.abspath(outputPath)

gives the following output:

'c:\\Users\\JEHOSHAPHAKSHAY\\Desktop'

This is in the hope that the code is more robust on different platforms and for different kinds of user inputs.

Recently I ran into an issue where this approach doesn't work as expected for a path that has one of the folders beginning with the letter t

That means; performing the following:

outputPath = 'c:\Users\JEHOSHAPHAKSHAY\Desktop\temp'
os.path.abspath(outputPath)

gives the following output:

'c:\\Users\\JEHOSHAPHAKSHAY\\Desktop\temp'

How do I get this to give me the correct path -

'c:\\Users\\JEHOSHAPHAKSHAY\\Desktop\\temp'

without doing a find and replace as that is not elegant?

Additionally, I don't mind using a raw string literal as long as I can prefix an existing string with a raw string literal.

Dustfinger
  • 1,013
  • 1
  • 18
  • 27
  • 1
    Is this only a problem with directory names starting with `t`? Have you tested with directory names starting with `n`, for example? Might be a string-escaping issue (e.g. `\t` resolves to a tab character after the preceding slash isn't escaped) – Chris Sprague Jul 17 '15 at 17:01
  • For a string literal, `'\t'` is interpreted as the TAB character. Whenever writing strings, never leave unescaped `\ `s. Always double them up. – Uyghur Lives Matter Jul 17 '15 at 17:07

1 Answers1

2

When os.path.abspath(file) parses a string, it first looks at \{char} to see if it's a special escaped character, and only then if it isn't one, does it treat it like a normal part of a path.

You need to treat your path as a raw string by adding r"...." to get the desired output:

path = r'c:\Users\JEHOSHAPHAKSHAY\Desktop\temp'
os.path.abspath(path)
>> 'c:\\Users\\JEHOSHAPHAKSHAY\\Desktop\\temp'

Basically, by saying making it a raw string you tell the interpeter to ignore special escaped characters and just look at each char as exactly that - just a character.

You can see this succinctly in @phihag's answer here

Community
  • 1
  • 1
xgord
  • 4,606
  • 6
  • 30
  • 51
  • That does work for me. Although it opens a whole new can of worms in that I already have a string and now need to convert it "raw" which this question asks: http://stackoverflow.com/questions/18707338/print-raw-string-from-variable-not-getting-the-answers. It doesn't look like that is easy to do for an existing string. – Dustfinger Jul 17 '15 at 17:28
  • it looks like maybe `stringVar.encode('string-escape')` might solve that issue: http://stackoverflow.com/questions/2428117/casting-raw-strings-python – xgord Jul 17 '15 at 17:32
  • although actually then it will escape the other preceding \'s too. hmmm.... let me think on that – xgord Jul 17 '15 at 17:35