Doubled backslashes in Windows paths

eryk sun eryksun at gmail.com
Fri Oct 28 20:41:14 EDT 2016


On Fri, Oct 28, 2016 at 8:04 PM, Gilmeh Serda
<gilmeh.serdah at nothing.here.invalid> wrote:
>
> You can use forward slash to avoid the messy problem.

There are cases in which you need to use backslash, such as extended
paths and command lines. Python 3's pathlib automatically normalizes a
Windows path to use backslash. Otherwise you can use
os.path.normpath().

>>>> target_dir = 'Desktop/2B_proc'
>>>> full_target = os.path.join(os.path.expanduser('~'), target_dir)

Don't assume the default location of a user's known folders. They can
all be relocated, either by domain group policy or individually using
the folder properties. Instead call SHGetKnownFolderPath or
SHGetFolderPath, e.g. to look up the value of FOLDERID_Desktop or
CSIDL_DESKTOP, respectively.

expanduser('~') is also used to locate configuration and data files,
such as "~\.python_history". On Windows, such files belong in a
subfolder of the user's hidden AppData folder. If they should roam
with a roaming profile, use %AppData%; otherwise use %LocalAppData%,
such as "%LocalAppData%\Python\python_history.txt". I prefer calling
SHGetKnownFolderPath instead of using the potentially stale
environment variables, but relocating these folders in a session is
uncommon.



More information about the Python-list mailing list