Behaviour of os.path.join

Beverly Pope countryone77 at gmail.com
Wed May 27 14:56:54 EDT 2020


I wasn’t going to say anything because I haven’t used MS Windows for years.  The OP wants to add a path separator at the end of a path.  Why the OP wants to do that doesn’t concern me.

OTOH, as others have already mentioned, the documentation explicitly says, "If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.”  While I may not understand WHY anyone would want that to occur, this was the way it was designed; it is not a bug.

The documentation also says, “The return value is the concatenation of path and any members of *paths with exactly one directory separator (os.sep) following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty.”  So, the module does allow one to add a path separator at the end of the path by simply adding an empty string as the last part of the path.  The following is on macOS (I don’t have a MS Windows machine):

>>> import os.path
>>> os.path.join('/Users/myID/a', 'b','c')
'/Users/myID/a/b/c'
>>> os.path.join('/Users/myID/a', 'b','c', '')
'/Users/myID/a/b/c/‘

So, it does work as advertised on Python 3.8 and all the OP should need to do is add that empty string to get the OP’s desired result.

Bev in TX






More information about the Python-list mailing list