Home > Software engineering >  How to add a leading slash when joining with os.path.join?
How to add a leading slash when joining with os.path.join?

Time:04-30

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?

CodePudding user response:

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.

  • Related