What is wrong with this os.path usage?
Ge开发者_运维技巧tting 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".
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.
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"
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.
精彩评论