Behaviour of os.path.join

Ben Bacarisse ben.usenet at bsb.me.uk
Wed May 27 11:53:55 EDT 2020


BlindAnagram <blindanagram at nowhere.com> writes:

> On 27/05/2020 13:30, Ben Bacarisse wrote:
>> BlindAnagram <blindanagram at nowhere.com> writes:
>> 
>>> The issue that I raised here was whether the behaviour of os.path.join()
>>> in treating the Windows directory separator '\\' as an absolute path
>>> should be considered a bug.
>> 
>> You think it should be considered to be a relative path?  The only
>> meaning that would give you want you wanted from
>> 
>>   os.path.join(<something>, '\\')
>> 
>> would be to treat it as being relative to the drive and to the
>> directory.  In other words you want '\\' to be a synonym for '.'  The
>> usual meaning of '\\' (outside of this specific function) is "root on
>> the current drive" but that can't sensibly be appended to any path.
>> 
>>> The behaviour of join came up for me when I tried to use the os.path
>>> functions to create a path that could only ever be used as a directory
>>> and never a file.  The only way that I found to designate a path as a
>>> directory path was to add '\\' at the end.  But this doesn't work in
>>> using os.path becaause the other os.path functions just strip it off and
>>> turn the directories back into files.
>> 
>> Nothing about the name can turn a directory into a file (or vice versa).
>> If c:\x\y is a file, calling it c:\x\y\ won't change that, but it might
>> give you an error when you try to access it.  That may be what you want.
>> If so, appending '.' is likely to be more portable.
>
> That is true if you know for sure how your path will be used.
>
> But if you don't, there is a world of difference between passing the
> paths 'name' and 'name\\' on for others to use. And in this situation it
> doesn't help when os.path functions strip the directory separator off.

As it should.  Relying on a trailing \ having the right effect is
brittle to say the least.

> This situation resulted in a bug that was surprisingly hard to track
> down because it created hidden files instead of directories as
> intended.

If so, the bug is not in os.path.join and trying to fix it by insisting
that a path have trailing \ may well just stacking up more problems for
later.

> After finding and correcting the '\\' that had been stripped off, the
> desired directories couldn't then be creaated on the target because
> hidden files were present with these names.

As I said, that's a dodgy thing to rely on.  It may be that you can't
fix the bug any other way (some aspect of the overall design may be
broken), but I would urge you to try.

There is well-known (*nix) software that relies on a/b/c/ meaning
something different to a/b/c but I don't know anyone who thinks this is
a good idea.  It causes no end of confusion.

-- 
Ben.


More information about the Python-list mailing list