Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how do I specify directory separator in os.path.join() function?

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'))
like image 440
Nicholas Avatar asked Mar 12 '23 13:03

Nicholas


2 Answers

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 instantiate PureWindowsPath.

like image 138
DocZerø Avatar answered Mar 18 '23 18:03

DocZerø


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'))
like image 42
zondo Avatar answered Mar 18 '23 18:03

zondo