file delimiter in dependency of os

T

Thomas Steffen

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
 
P

Peter Otten

Thomas said:
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
 
P

Peter Hansen

Peter said:
Note that backslashes are only needed for the conventional user experience,
Windows is happy with "/", too. Have a look at os.path.normcase() which

Or, to be more practical, backslashes are needed for commands that are
passed to the MS-DOS shell with os.system() and friends. Any other
way of getting the paths to the OS should work with forward slashes.

-Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top