file delimiter in dependency of os

Peter Otten __peter__ at web.de
Sun Nov 2 06:08:30 EST 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):

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

usage:

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.

Peter







More information about the Python-list mailing list