os.path.join doubt

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Feb 3 07:31:49 CET 2011


On Wed, 02 Feb 2011 20:46:12 -0800, harryos wrote:

> In windows ,I tried this
> 
> p1 = "C:\Users\me\Documents"
> p2 = "..\Pictures\images\my.jpg"
> 
> print os.path.join(p1,p2)
> This gives
> 'C:\\Users\\me\\Documents\\..\\Pictures\\images\\my.jpg'
> 
> I expected I would get
> 'C:\\Users\\me\\Pictures\\images\\my.jpg'
> 
> I thought os.path.join would join the paths more intelligently..Any idea
> why this happens ?

You thought wrong.

os.path.join just joins what you tell it to, it doesn't normalise the 
path. If you want to normalise, call os.path.normpath:


>>> os.path.normpath('x/y/../z')
'x/z'


As for why, it's because joining and normalising are two different 
operations that you may wish to keep separate, so they require two 
separate functions.


BTW, Windows accepts / as well as \ as a path separator. You will have 
far fewer headaches if you use that.



-- 
Steven



More information about the Python-list mailing list