Python os.path.join() Method



The Python os.path.join() method is used to construct a path by joining one or more path components.

The method takes multiple path components (strings) and joins them together with appropriate directory separators (/ or \) depending on the operating system. If any of the provided path components contain absolute path information (e.g., a leading / or C:\), the previous components are discarded, and the resulting path starts with that absolute path.

Syntax

Following is the basic syntax of the Python os.path.join() method −

os.path.join(path1[, path2[, ...]])

Parameter

This method accepts a strings as parameter representing the path components to be joined. Multiple path components can be provided as separate argument.

Return Value

The method returns a string representing the combined path.

Example

In the following example, we are joining two path components, "/path/to" and "file.txt", to form a path using the join() method −

import os
path1 = "/path/to"
path2 = "file.txt"
joined_path = os.path.join(path1, path2)
print(joined_path)  

Output

The output obtained is as follows −

/path/to/file.txt

Example

Here, we are joining two path components, "/path/to" and "/absolute/directory". Since the second component is an absolute path, it overrides the first one −

import os
path1 = "/path/to"
path2 = "/absolute/directory"
joined_path = os.path.join(path1, path2)
print(joined_path) 

Output

Following is the output of the above code −

/absolute/directory

Example

If one of the arguments is empty, the join() method returns the non-empty argument as the result.

In here, we are joining "/path/to" with an empty string "" −

import os
path1 = "/path/to"
path2 = ""
joined_path = os.path.join(path1, path2)
print(joined_path) 

Output

We get the output as shown below −

/path/to/

Example

Now, we are joining two path components "/usr/" and "/local/bin" using the join() method. Even though the first component ends with a separator, the method correctly handles it, resulting in '/local/bin' −

import os
path1 = ""
path2 = "file.txt"
joined_path = os.path.join(path1, path2)
print(joined_path)  

Output

The result produced is as follows −

file.txt
os_path_methods.htm
Advertisements