The os module in the standard library includes a sub module known as path which is useful for working with and manipulating file and directory paths.

The join() function in the path module is used to  join two or more path components into a single path. The function uses the os.sep character  to delimit the path components. The os.sep character is platform-specific and  depends on the operating system being used. For example 

On a Windows system

import os

print(os.sep)

 \ 

On a Unix system

import os

print(os.sep)

The join() function joins the path components using the os.sep character as the separator.

path.join(path, *paths)
path The base path
*paths Arbitrary  path segments to be joined. 
from os import path

segments = ('Desktop', 'Files', 'Images', 'me.png')

p = path.join(*segments)
print(p)

In the above example:

  • We imported the path submodule from the os module
  • We defined a tuple containing the segments to be joined.
  • We used the path.join() function to create  a path from the segments unpacked from the tuple. The unpacking operator(*) ensures that each element in the tuple is passed to the join function as an individual argument.

When a path segment in the arguments to be joined starts with  the os.sep character, it will be treated as a full path and all the segments that precedes it will be ignored. This means that  the resulting path will begin from  the beginning of the rightmost segment that begins with the os.sep character.

from os import path

segments = ('one', 'two', '/three', 'four')

p = path.join(*segments)
print(p)

In the above example, the third segments starts with the os.sep character(on unix i.e /), therefore all the segments that comes before it are ignored.

from os import path

paths = [('/one', 'two', 'three', 'four'),
('one', '/two', 'three', 'four'),
('one', 'two', '/three', 'four'),
('one', 'two', 'three', '/four')]

for p in paths:
    print(path.join(*p))

The above example demonstrates well how segments beginning with the platforms's os.sep character are treated as full path and how any segments preceding the rightmost one are not included in the resulting path.

Creating absolute paths

We can use the join() function to create absolute paths by joining relative paths with a base path. We can get the base path by getting the current directory using the getcwd() function.

on Windows system with Desktop as the working directory

import os
from os import path

cwd = os.getcwd()
dir = 'project\\media\\'
file = 'example.png'

#join the segments
p = path.join(cwd, dir, file)

print(p)

 C:\Users\John\Desktop\project\media\example.png

 In the above example:

  • We used the os.getcwd() to get the current working directory.
  • The dir variable represents the path to where the file is relative to the working directory
  • The file variable represents the name of the file
  • we used the join() function to get the absolute path to the example.png file.