Behaviour of os.path.join

BlindAnagram blindanagram at nowhere.com
Wed May 27 09:41:16 EDT 2020


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.

This situation resulted in a bug that was surprisingly hard to track
down because it created hidden files instead of directories as intended.
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.


More information about the Python-list mailing list