I tried the code as below, attempting to change directory separator to forward slash /
but still stuck in the backslash \
. The documentation says the function joins paths using directory separator os.sep
, but this didn't work in my case.
import os
os.sep = '/'
print(os.sep)
print(os.path.join('.', 'path'))
I think this answers the questions why Python uses a particular separator.
That said, you can use the Pathlib
module to construct your paths and specify whether you want a Posix or Windows path.
Example:
from pathlib import PurePosixPath, PureWindowsPath
print(PurePosixPath('some', 'silly', 'long', 'path'))
>> some/silly/long/path
print(PureWindowsPath('some', 'silly', 'long', 'path'))
>> some\silly\long\path
Make sure you use the pure
version of PosixPath
and WindowsPath
. If you're trying to use WindowsPath
on a Posix system, you'll get the following error:
NotImplementedError: cannot instantiate 'WindowsPath' on your system
This is also specified in the docs:
If you want to manipulate Windows paths on a Unix machine (or vice versa). You cannot instantiate a
WindowsPath
when running on Unix, but you can instantiatePureWindowsPath
.
You can take a look at the source code for the different operating systems. For example, the Mac version is:
def join(s, *p):
path = s
for t in p:
if (not s) or isabs(t):
path = t
continue
if t[:1] == ':':
t = t[1:]
if ':' not in path:
path = ':' + path
if path[-1:] != ':':
path = path + ':'
path = path + t
return path
You can see that it is placed directly into the function. It does not depend on os.sep
. Each Python installation includes the os.path
functions for every operating system. They are available in the Python directory under macpath.py
, ntpath.py
, and posixpath.py
. If you look at each one, you will notice that the posixpath
module has what you want:
import posixpath
print(posixpath.join('.', 'path'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With