Reputation: 388
I am trying to open a file dialog to a directory other than the one in which I am working. I tried this:
dlg = wx.FileDialog(self, "Open", style=wx.FD_OPEN)
dlg.SetDirectory("C:\Users\tech\Desktop\Circuit Design Tool\Program Files")
dlg.ShowModal()
file_name = dlg.GetPath()
dlg.Destroy()
and this:
directory = "C:\Users\tech\Desktop\Circuit Design Tool\Program Files"
dlg = wx.FileDialog(self, "Open", directory, style=wx.FD_OPEN)
dlg.ShowModal()
file_name = dlg.GetPath()
dlg.Destroy()
but they both open to the directory in which I am working. Does anyone know what I'm doing wrong?
Upvotes: 0
Views: 2244
Reputation: 952
Late to the party, but since it might help others with the same problem:
As nepix32 correctly explained, the backslashes need to be escaped. I found that this is still insufficent to get it working, but it started to work once I included an additional trailing backslash, so both this:
dlg = wx.FileDialog(self, "Open", style=wx.FD_OPEN)
dlg.SetDirectory("C:\\Users\\long\\path\\to\\Program Files\\")
and this:
directory = "C:\\Users\\long\\path\\to\\Program Files\\"
dlg = wx.FileDialog(self, "Open", directory, style=wx.FD_OPEN)
work for me (note the trailing \\
at the end of the path).
If you use this, a raw string isn't sufficient to disambiguate a last backslash from a literal quote sign, so you have to escape the backslashes instead. Or use forward slashes.
Upvotes: 0
Reputation: 2096
The following works for me:
dataDir = r"C:\Users\tech\Desktop\Circuit Design Tool\Program Files"
with wx.FileDialog(None, 'Open', dataDir,
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as dlg:
if dlg.ShowModal() == wx.ID_OK:
dbfilename = dlg.GetPath()
dataDir, dbFile = os.path.split(dbfilename)
Don't know why SetDirectory does not work, but in the other one you are not giving a default dir, see: http://wxpython.org/Phoenix/docs/html/FileDialog.html?highlight=filedialog#api-class-api
Upvotes: 0
Reputation: 3062
This has nothing to do with wxPython:
Try using this path with e. g. open(...)
and it will also not work.
Reason: Som backslash/byte combinations will result in interpretation as string literals, e. g. "\t"
as tab character. To avoid this, you can declare the string as "raw" with the r
prefix, like this:
"\t" == r"\t"
Of course, if you are on windows and the path contains unicode characters, it will get interesting again :)
Upvotes: 1