I’ve encountered a peculiar issue with os.path.join in Python. When I add a forward slash (/) in front of the directory variable and pass it to os.path.join, the result is just /Test_directory. However, if I don’t include the forward slash, the full path /home/mvnd3x/Desktop/Test_directory is printed. The same does not happens if I add a forward slash at the end of the parent_directory. Here’s the code I’m working with:
import os
directory = "/Test_directory"
parent_directory = "/home/mvnd3x/Desktop"
path = os.path.join(parent_directory, directory)
print(path)
Expected Output
/home/mvnd3x/Desktop/Test_directory
Actual Output
/Test_directory
Could someone explain why adding a forward slash in front of the directory variable or behind parent_directory variable causes this different behavior? How should I properly use os.path.join to avoid this issue?
Thanks in advance for your help!