Behaviour of os.path.join

Rhodri James rhodri at kynesim.co.uk
Tue May 26 13:23:34 EDT 2020


On 26/05/2020 18:07, BlindAnagram wrote:
> On 26/05/2020 17:46, MRAB wrote:
>> On 2020-05-26 16:48, BlindAnagram wrote:
>>> On 26/05/2020 16:22, Ben Bacarisse wrote:
>>>> BlindAnagram <blindanagram at nowhere.com> writes:
>>>>
>>>>> I came across an issue that I am wondering whether I should report
>>>>> as an
>>>>> issue.  If I have a directory, say:
>>>>>
>>>>>    base='C:\\Documents'
>>>>>
>>>>> and I use os.path.join() as follows:
>>>>>
>>>>>    join(base, '..\\..\\', 'build', '')
>>>>
>>>> It rather defeats the purpose of os.sep if you include it in a part of
>>>> the path.  What you mean is better expressed as
>>>>
>>>>    join(base, '..', '..', 'build', '')
>>>>
>>>> (and base includes it too, but I can't suggest an alternative because I
>>>> don't know your intent is far as defaults go.)
>>>
>>> Thanks for your input but while that part of my path may not be to your
>>> liking, it works fine and does not seem to be relevant to my concern,
>>> which is that join appears to treat os.sep as an absolute path, which it
>>> is not.
>>>
>> If it starts with the path separator, then it's absolute (well, absolute
>> on that drive).
> 
> Agreed.  I did not think that I needed to add this exception to my
> comment as I thought from the the context that it would be clear that I
> was questioning how it worked at the end of a path, not when used at its
>   start.

But you aren't talking about the end of the (finished) path, you are 
talking about the start of the final path component you pass to 
os.path.join(), "\\".  As the documentation says, "If a component is an 
absolute path, all previous components are thrown away and joining 
continues from the absolute path component."  Since "\\" is an absolute 
path component, all the previous components are thrown away and you are 
left with just "\\".

-- 
Rhodri James *-* Kynesim Ltd


More information about the Python-list mailing list