1

Getting an unexpected result with os.path on Windows XP, Python 2.6.6:

a = "D:\temp\temp.txt"
os.path.dirname(a)
>>> 'D:' # Would expect 'D:\temp'
os.path.normpath(a)
>>> 'D:\temp\test.txt'
os.path.basename(a)
>>> '\temp\test.txt' #Would expect 'test.txt'
a.replace("\\", "/")
>>>'D:\temp\test.txt' # Would expect 'D:/temp/test.txt'

Can someone explain what is going on? How can I get the correct / expected behaviour? Why can't I replace the backslashes with front slashes?

EDIT: I am getting this path from a text field in a wxPython app, so it comes as a string with unescaped backslashes, and I can't seem to replace them with "replace".

3 Answers 3

9

You aren't escaping your backslashes. Either use \\ instead of \, or use raw strings, e.g:

a = r"D:\temp\temp.txt"

In your unescaped strings, the \t is interpreted as a tab character.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, is there a way to do this inline, so that I can do something like os.path.isdir(r'a')?
If you pass the os.path.dirname a File object instead of a string, you won't need to worry about the escaping - you only have to bother with escaping the backslash or using raw input because you are passing a string. Is there any way you can get around passing the string?
@Benjamin: Escaping and raw strings are only relevant to string literals contained in Python code, not to values you read from the user. If you say you received your string from a text field then maybe your problem is different, but it's impossible to tell what it is from the information presented in the question.
@IamChuckB: not that I know, this is coming from a textCtrl.GetValue() so it comes as a string.
@Benjamin: After getting the string input, try doing something like print repr(a). It should show escaped backslashes if everything is OK.
|
0

Your problem is with the assignment of a. You need to escape the backslashes in the string Try this instead:

a = "D:\\temp\\temp.txt"

Comments

0

Using a.encode('string-escape') seems preferable to other solutions because i) it can be done inline and ii) it doesn't add extra single/double-quotes.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.