file delimiter in dependency of os

Peter Otten __peter__ at
Sun Nov 2 12:08:30 CET 2003

Thomas Steffen wrote:

> Hallo,
> I have pathes with different file delimiters
> e.g.
> /root/dir\mydir/myfile
> C:\xxx/hh\gggg/myfile
> How can I change the mistaken file delimiters in dependency of the
> used os (win or unix) effectively?
> unix: /root/dir\mydir --> /root/dir/mydir
> win: C:\xxx/hh\gggg/myfile --> C:\xxx\hh\gggg\myfile
> Thanks for your hints Thomas

Note that backslashes are only needed for the conventional user experience,
Windows is happy with "/", too. Have a look at os.path.normcase() which
should meet your needs if you are consistently using forward slashes in
your application. Otherwise the following tiny module might do (untested):

import os
if == "posix":
    def normslash(path):
        return path.replace("\\", "/")
elif == "nt":
    def normslash(path):
        return path.replace("/", "\\")
   raise Exception("OS not supported: %s" %")


import plat
path = plat.normslash(path)

By the way, if you are building paths like so:

path = folder + "/" + filename

Use os.path.join() instead. It will automatically select the right separator
for you.


More information about the Python-list mailing list