Why does Tkinter's askdirectory() return forward slashes on Windows?
python, python-3.x, tkinter, windows
Solution
Edit:
I'm going to edit my answer because I don't think I was very clear.
To start, `tkinter.filedialog.askdirectory` always uses forwardslashes in the path it returns. So, what you are seeing is not a bug--it is a result of the way that the function was designed. Moreover, this behavior occurs on both Windows and *nix systems.
Now, there doesn't seem to be anything out there that directly states why `askdirectory` was built this way. Tkinter always did have a reputation for being poorly documented. ;)
However, there are a few things to consider:
`\` is a special character in Python strings. It creates an escape sequence. Thus, if the path returned by `askdirectory` contained backslashes, it is only expected that it would cause problems. Or, if it didn't, you would still need some safety code to prevent them.
Python works just fine on both Windows and *nix systems with forwardslashes in paths. As an example, this code:
open("C:/path/path/")
works identically to this:
open(r"C:\path\path")
The only difference is, with the second method, you have to handle escape sequences. I did this by using a raw-string, which is explained in the link above. However, it is a lot easier to just use forwardslashes.
Because Tkinter is cross-platform, it is both convenient and efficient to use a normalized path construct internally. Therefore, why not use the one that works on both Windows and *nix systems without any escaping necessary?
If you must have a native path for your application, Python already has built-in functions to make it. These can be found in the `os.path` module.
With these reasons in mind, it only seems logical to build `askdirectory` to use forwardslashes.
Problem
Setup: Windows 7 Python Version: 3.3 I'm making a crossplatform application, and I have the user give a directory using the `askdirectory()` method in Tkinter's `tkinter.filedalog.askdirectory` module. This works fine, except for some reason on Windows it's giving me forward slashes. Windows uses backslashes, not forward slashes, so when I try to save a text file with native file slashes (config file stores the directory so it has an ending slash I have to add), it looks goofy: ``` F:/Pictures/Wallpapers\ ``` The code I use to put the native slash is just `os.sep`, which is the current system's native directory separator, which is different on *nix and windows. ``` def getDownloadPath(self): pathdir=askdirectory() if pathdir=='': return #cancel pathdir+=os.sep self.download_location.delete(0,END) self.download_location.insert(0,pathdir) ``` Is there a reason the folder chooser doesn't return native slashes? I googled around and saw no answers.