views:

81

answers:

3

hi,

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:\\Documents 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

A: 

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

path = "C:\\Documents and Settings\\tchan\\Desktop\\InputFile.xls"
mipadi
+1  A: 

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)
James Snyder
perfect, thats the raw type conversion i didn't know about (no such thing as a raw_string()). And normpath is smart enough to reduce 2 slashes here and no slashes there. Thanks!
PPTim
+1  A: 

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

iondiode
interesting.. what does encode do?
PPTim
in this case , not much, it adds double escapes much like @James' answer above.
iondiode