2023-01-10

os.path.join()

What is os.path.join()

os.path.join() is a method in Python programming language, which combines one or more path names into a single path. It is available in the os.path module where os stands for the operating system. This method takes care of any differences in the way file paths are structured across Windows, Linux, and Mac OS.

Joining Path

To join any two parts of a path, the os.path.join() function is used. It takes in two arguments, both strings representing the parts of the path to be joined. Here's an example:

python
import os
path = os.path.join("myDirectory", "myFile.txt")
print(path)

The above script will output myDirectory/myFile.txt or myDirectory\myFile.txt, depending on the operating system.

Joining Multiple Paths

os.path.join() isn't just limited to two paths; you can join as many as you want. Python will combine them all together. Here's an example of how this can work:

python
import os
path = os.path.join("dir1", "dir2", "dir3", "file.txt")
print(path)

This will output dir1/dir2/dir3/file.txt or dir1\dir2\dir3\file.txt depending on the operating system you are working with.

Joining Paths in List Format

Sometimes, you might have your paths stored in a list format. os.path.join() can still handle this scenario. You simply need to unpack the list using the * operator. Here's an example:

python
import os
dirs = ["dir1", "dir2", "dir3", "file.txt"]
path = os.path.join(*dirs)
print(path)

This will output the same as the previous example.

Ryusei Kakujo

researchgatelinkedingithub

Focusing on data science for mobility

Bench Press 100kg!