Behaviour of os.path.join

BlindAnagram blindanagram at nowhere.com
Tue May 26 13:23:50 EDT 2020


On 26/05/2020 16:59, Mats Wichmann wrote:
> On 5/26/20 8:56 AM, BlindAnagram wrote:
>> 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', '')
>>
>> I obtain as expected from the documentation:
>>
>> 'C:\\Documents\\..\\..\\build\\'
>>
>> But if I try to make the directory myself (as I tried first):
>>
>>   join(base, '..\\..\\', 'build', '\\')
>>
>> I obtain:
>>
>> 'C:\\'
>>
>> The documentation says that an absolute path in the parameter list for
>> join will discard all previous parameters but '\\' is not an absoute path!
> 
> But it is - an absolute path is one that starts with the pathname separator.

In a string giving a file path on Windows '\\' is recognised as a
separator between directories and not as an indicator that what follows
is an absolute path based on the drive letter (although it might, as you
say, imply a drive context).

> The concept of paths is ugly in Windows because of the drive letter - a
> drive letter is not actually part of a path, it's an additional piece of
> context.  If you leave out the drive letter, your path is relative or
> absolute within the current drive letter; if you include it your path is
> relative or absolute within the specified drive letter.  So Python has
> behaved as documented here: the indicator for an absolute path has
> discarded everything (except the drive letter, which is necessary to
> maintain the context you provided) which came before it in the join.

This is not consistent with how other file management functions in
os.path operate since they willingly accept '\\' as a directory separator.

> If indeed you're seeking a path that is terminated by the separator
> character, you need to do what you did in the first example - join an
> empty string at the end (this is documented).  The terminating separator
> _usually_ isn't needed.  Sadly, sometimes it appears to be...



More information about the Python-list mailing list