[issue41509] ntpath.relpath behaves differently on Windows with trailing spaces

Eryk Sun report at bugs.python.org
Sat Aug 8 15:15:05 EDT 2020


Eryk Sun <eryksun at gmail.com> added the comment:

> I suspect the Windows version is using some API that strips whitespace 
> from the filename before performing a relative path. 

When normalizing a path, the Windows API strips trailing dots and spaces from the final component. Apparently it also strips a single trailing dot from other components if the dot is preceded by any character other than a dot. For example:

    >>> nt._getfullpathname('foo../bar./bam. . .')
    'C:\\foo..\\bar\\bam'

The way to create or open a file or directory with a name that ends with a dot or space is to prefix the path with exactly "\\\\?\\". However, it is strongly advised to never create a file or directory with such an abnormal name. Note that this prefix only affects using a path in an open/create context. It doesn't prevent an explicit normalization, such as the following:

    >>> nt._getfullpathname('\\\\?\\C:/foo../bar./bam. . .')
    '\\\\?\\C:\\foo..\\bar\\bam'

> I wouldn't expect Windows to be performing normalization of paths in 
> relpath, but it seems it does. 

ntpath.relpath calls ntpath.abspath, which calls nt._getfullpathname in Windows. On POSIX systems, ntpath.abspath is ntpath._abspath_fallback.  The latter and ntpath.normpath need to be improved to better implement Windows path normalization. 

normpath should not exclude paths that start with '\\\\.\\' and '\\\\?\\', and it should trim trailing spaces and dots from component names to match how Windows normalizes a path. 

_abspath_fallback should default to the root directory for drive relative paths (e.g. "C:foo" -> "C:\\foo"). It should also substitute a device path if the final component in a relative or drive-letter path (but not a UNC path or device path) matches a known DOS device name. Matching a DOS device name ignores everything after a dot or colon that's preceded by zero or more spaces (e.g. "con .anything" -> "\\\\.\\con" and "nul:anything" -> "\\\\.\\nul").

----------
nosy: +eryksun

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue41509>
_______________________________________


More information about the Python-bugs-list mailing list