开发者

parse this directory path without losing slash

I have a wxPython application. I am taking in a directory path from a textbox using GetValue().

I notice that while trying to write this string to a variable:

"C:\Documents and Settings\tchan\Desktop\InputFile.xls",

python sees the string as

'C:\\Document开发者_StackOverflows and Settings\tchan\\Desktop\\InputFile.xls' (missing a slash between "Settings" and "UserName).

More info:

The directory path string is created by the "open file" dialog, which creates a standard 'choose file' dialog you see in any 'open' function in a text processor. The string is written to a textbox and read later when the main thread begins (in case the user wants to change it).

EDIT: I realise that the problem comes from the '\t' being seen as a "tab" instead of normal forward slash. However I don't know how to work past this, since


I suspect there's a different way to get that path from wx that would avoid this issue, since it seems like this would be a fairly common problem. That said, there are a few ways to fix a mangled path like you describe, by converting the string you have to a raw string.

rawpath = "%r" % path

The resulting rawpath will likely be somewhat messy since it will probably add extra escapes to the backslashes and give you something like:

"'C:\\\\Documents and Settings\\tchan\\\\Desktop\\\\InputFile.xls'"

It seems like os.path.normpath will clean that up though.

import os.path
os.path.normpath(rawpath)


not saying this is the correct solution, but you can

x = "C:\tmp".encode('string-escape')
x
'C:\\tmp'

better, if you are using the file dialog

os.path.join(dlg.GetDirectory(),dlg.GetFilename())

where dlg is your dialog


You have to escape the slashes. \\ will store a literal \ in the string:

path = "C:\\Documents and Settings\\tchan\\Desktop\\InputFile.xls"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜