The proposed solutions are interesting and offer a good reference, however they are only partially satisfying. It is ok to manually add the separator when you have a single specific case or you know the format of the input string, but there can be cases where you want to do it programmatically on generic inputs.
With a bit of experimenting, I believe the criteria is that the path delimiter is not added if the first segment is a drive letter, meaning a single letter followed by a colon, no matter if it corresponds to a real unit.
For example:
import os
testval = ['c:','c:\\','d:','j:','jr:','data:']
for t in testval:
print ('test value: ',t,', join to "folder"',os.path.join(t,'folder'))
test value: c: , join to "folder" c:folder
test value: c:\ , join to "folder" c:\folder
test value: d: , join to "folder" d:folder
test value: j: , join to "folder" j:folder
test value: jr: , join to "folder" jr:\folder
test value: data: , join to "folder" data:\folder
A convenient way to test for the criteria and apply a path correction can be to use os.path.splitdrive
comparing the first returned element to the test value, like t+os.path.sep if os.path.splitdrive(t)[0]==t else t
.
Test:
for t in testval:
corrected = t+os.path.sep if os.path.splitdrive(t)[0]==t else t
print ('original: %s\tcorrected: %s'%(t,corrected),' join corrected->',os.path.join(corrected,'folder'))
original: c: corrected: c:\ join corrected-> c:\folder
original: c:\ corrected: c:\ join corrected-> c:\folder
original: d: corrected: d:\ join corrected-> d:\folder
original: j: corrected: j:\ join corrected-> j:\folder
original: jr: corrected: jr: join corrected-> jr:\folder
original: data: corrected: data: join corrected-> data:\folder
it can be probably be improved to be more robust for trailing spaces, and I have tested it only on windows, but I hope it gives an idea.
See also Os.path : can you explain this behavior? for interesting details on systems other then windows.