Behaviour of os.path.join

Mats Wichmann mats at python.org
Tue May 26 11:59:59 EDT 2020


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.

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.

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