'How to add a leading slash when joining with os.path.join?

my_list = ['', 'drive', 'test', filename]

path = os.path.join(*my_list)

Result for path is drive/test/filename

The desired result for path would be /drive/test/filename (with the leading slash, because i do have a '', at the start of my_list

I ended up using os.path.sep.join(my_list), which produces /drive/test/filename with the leading slash as desired, but i was wondering if there is a better way to do this?



Solution 1:[1]

For absolute paths, the initial / is not really a delimiter so much as the name of the root directory. You could do the following:

my_list = ['/', 'drive, 'test', filename]
path = os.path.join(*my_list)

Whether altering how you generate my_list is cleaner than your current solution is, I suspect, a matter of opinion.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chepner