How to join two paths in Python using os.path.join()?

Published on Aug. 22, 2023, 12:17 p.m.

To join two paths in Python, you can use the os.path.join() method. This method takes multiple arguments and returns a single path string constructed by concatenating the input arguments with the appropriate separator for the operating system. Here is an example:

import os

path1 = "/path/to/folder"
path2 = "file.txt"
full_path = os.path.join(path1, path2)

print(full_path)

This will output:

/path/to/folder/file.txt

In this example, os.path.join() concatenates path1 and path2 to produce a single path string that represents the location of file.txt relative to path1. Note that you can pass multiple arguments to os.path.join(), and it will concatenate them all to produce a single path string.

Using os.path.join() is preferable to manually concatenating path strings because it automatically handles differences in path separators between operating systems. Additionally, it can join a varying number of path components without having to modify the code each time.

Tags: