[Python-ideas] os.path.isparent and os.path.ischild

Steven D'Aprano steve at pearwood.info
Fri Jul 8 11:57:04 CEST 2011


Oleg Broytman wrote:
> On Fri, Jul 08, 2011 at 06:00:26PM +1000, Steven D'Aprano wrote:
>> def isparent(path1, path2):
>>     "Returns True if path1 is a parent of path2."
>>     return os.path.commonprefix([path1, path2]) == path1
> 
>>>> isparent('C:\\Program Files', 'C:/Program Files/Python')
> False
> 
>    Oops...


Why is that an oops? On my Linux system, I can create a file 
"C:\\Program Files" which is very different from the path "C:/Program 
Files/Python" (two directories and a file). Other operating systems may 
do things differently, but for me, they have no path in common:

 >>> os.path.split('C:\\Program Files')
('', 'C:\\Program Files')
 >>> os.path.split('C:/Program Files/Python')
('C:/Program Files', 'Python')


If you want to normalise the paths first, normalise them. That's what 
normpath and normcase are for. The other path manipulation functions, 
like os.path.split(), don't normalise paths before operating on them. 
Why should isparent and ischild?



-- 
Steven



More information about the Python-ideas mailing list