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.
- Relative path: Use “/” to get the relative path.
- 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.
- path: It is a path-like object representing a file system path.
- *path: It is a path-like object representing a file system path. It represents the path components to be joined.
import os path = "/Users" cwd = os.getcwd() joinedPath = os.path.join(path, cwd, "app.py") print(joinedPath)
In this example, you can see that we joined three paths.
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.