How to Join Multiple Paths in Python

The os.path.join() function constructs a pathname out of one or more partial pathnames.

What is a file path in Python?

A file path in Python is a sequence of file and folder names. There are two types of the file path.

  1. Relative path: Use “/” to get the relative path.
  2. Absolute path: Use the os.getcwd() function to get the absolute path of the current working directory. 

Join Multiple Paths in Python

To join multiple paths in Python, use the os.path.join() method. The os.path.join() function concatenates different path components with exactly one directory separator (“/”) following each non-empty part except the last path component.

The os.path.join() method doesn’t take a list as an argument; it has to be separate arguments. Python os.path.join() method integrates one or more pathnames into a single path.

To work with os.path.join() method in Python script, and you need to first import os module. The os module contains functions to get information on local directories, files, processes, and environment variables.

Syntax

os.path.join(path, *paths) 

Arguments

  1. path: It is a path-like object representing a file system path. 
  2. *path: It is a path-like object representing a file system path. It represents the path components to be joined.

Example

import os

path = "/Users"
cwd = os.getcwd()
joinedPath = os.path.join(path, cwd, "app.py")
print(joinedPath)

Output

/Users/krunallathiya/Desktop/Code/Python/app.py

In this example, you can see that we joined three paths.

  1. “/Users”
  2. cwd
  3. app.py

Using os.path.join() function, it combines path names into one complete path. This means that you can merge multiple parts of a path into one.

That’s it for this tutorial.

Leave a Comment