What is os.path.join Python module

There will be time the need to get information or execute on local directories and file.

Task like read and connect to database is one of the example that commonly used to create a function using os.path.join() module.

A project read two files in different directories using os.path.join()

I am going to explain a bit.

We are going to create two folders. First directory named as newfolder while another directory inside the root folder named as subfolder. Besides we got our subfolder inside our newfolder we are going to create three different files which is test.txt and task.py into our root folder and another one readme.txt into our subfolder that we had created just now. Here is what it looks like.

|- newfolder/
    |- test.txt
    |- task.py
    |- subfolder/
        |- readme.txt

Let’s start with create a directory/folder

$ mkdir newfolder

We create our folder name newfolder

$ cd newfolder

Next, we move to newfolder. Our newfolder will be our main working directory. Any files or directories inside our main working directory is also call as root folder or directory.

$ mkdir subfolder

Now, create three text files

$ touch test.txt task.py subfolder/readme.txt

Put some text into files

I am going to put Zen-of-Python into these files. Let put some text for test.txt

Read from -> test.txt
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.

Put another few lines of text for readme.txt

Read from -> subfolder/readme.txt
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.

Create script to read files

Now, let put some code to read each of these files test.txt and readme.txt.

Are you ready? If yes, then let’s get going.

# task.py

# 1st task - read file test.txt

with open('test.txt') as f:
    lines = f.readlines()
    print(lines)

We code our task.py script to read each line from test.txt. Then, we run into Python interpreter. I am going to run it into terminal.

$ python3 task.py

This will results an output:

['Read from -> test.txt\n', 'Beautiful is better than ugly.\n', 'Explicit is better than implicit.\n', 'Simple is better than complex.\n', 'Complex is better than complicated.\n', 'Flat is better than nested.\n']

Now, let’s code to into task.py read our next file readme.txt

# task.py

# 1st task - read file test.txt

with open('test.txt') as f:
    lines = f.readlines()
    print(lines)

# 2nd task - read file readme.txt

with open('subfolder/readme.txt') as f:
    lines = f.readlines()
    print(lines)

Our next result.

['Read from -> test.txt\n', 'Beautiful is better than ugly.\n', 'Explicit is better than implicit.\n', 'Simple is better than complex.\n', 'Complex is better than complicated.\n', 'Flat is better than nested.\n']
['Read from -> subfolder/test.txt\n', 'Sparse is better than dense.\n', 'Readability counts.\n', "Special cases aren't special enough to break the rules.\n", 'Although practicality beats purity.\n', 'Errors should never pass silently.\n', '\n']

Ok, so far we got only two files to read.

What if we got multiple files and few subdirectories that we need to do the same task. Here is where os.path.join() becomes handy. Instead of typing directly into open() we can supply a variable inside the open() parentheses.

Use-os.join.path()-module

# task.py # import module import os # create variable to path using os.join.path() path_to_file = os.path.join('subfolder/', 'readme.txt') # 1st task - read file test.txt with open('test.txt') as f: lines = f.readlines() print(lines) # 2nd task - read file readme.txt # with open('subfolder/readme.txt') as f: with open(path_to_file) as f: lines = f.readlines() print(lines)

We got few steps here:

  • 1st: We import os module
  • 2nd: Create variable path named as path_to_file with os.path.join() method.
  • 3rd: Inside join() we put 'subfolder/' and 'readme.txt' as parameters.
  • 4th: Replace into open() a variable path_to_file that had created.

Now, let’s print() variable path_to_file by adding another line as below:

print(path_to_file)

Output to print variable path_to_file

subfolder/readme.txt

Besides that we can also split it into few component such like this.


# split to two parts as variables
path_to = 'subfolder/'
file_ = 'readme.txt'

# assign variables path_to and file_ into join()
fullpath = os.path.join(path_to, file_)

Here we split it up into two parts which is path_to and file_. Then we put both variables as parameters into join() method.

Here is the full source code.

# task.py

# import module
import os

# create variable to path using os.join.path()
path_to_file = os.path.join('subfolder/', 'readme.txt')

# split to two parts as variables
path_to = 'subfolder/'
file_ = 'readme.txt'

# assign variables path_to and file_ into join()
fullpath = os.path.join(path_to, file_)

# 1st task - read file test.txt

with open('test.txt') as f:
    lines = f.readlines()
    print(lines)

# 2nd task - read file readme.txt

# with open('subfolder/readme.txt') as f:
# with open(path_to_file) as f:
with open(fullpath) as f:
    lines = f.readlines()
    print(lines)

print(path_to_file)

Conclusion

os.path.join() is useful into managing our project link, directory or files.