Python: How to add path separator to beginning of path

I’m looking for the cleanest way to add a path separator to the beginning of a relative path if it’s not already there.

So for example my/path should result in /my/path/.

The way I do it now is the following:

import os
os.sep+'my/path'

This approach works but when a non relative path is passed it will also add the separator which is something I want to avoid.

Suggestions?

Answer

Try os.path.join with the root directory as its first argument.

>>> import os
>>> os.path.join('/', '/tmp')
/tmp
>>> os.path.join('/', 'tmp')
/tmp

Leave a Reply

Your email address will not be published. Required fields are marked *