[Baypiggies] os.path.join unexpected behavior on windows

William Deegan bdbaddog at gmail.com
Wed Aug 27 02:02:12 CEST 2008


Greetings,

I have the following (simplified) code:
import os.path

z='/build'
x='m:/billdeeg.scons1'
print  "X=>%-20s z=>%-10s Joined path is=>%s"%(x,z,os.path.join(x,z))

x='m:/billdeeg.scons1/'
print  "X=>%-20s z=>%-10s Joined path is=>%s"%(x,z,os.path.join(x,z))

x='m:/billdeeg.scons1'
print  "X=>%-20s z=>%-10s Joined path is=>%s"%(x,z,os.path.join(x,z))

z='build'
print  "X=>%-20s z=>%-10s Joined path is=>%s"%(x,z,os.path.join(x,z))

z='/build'
x='n:'
print  "X=>%-20s z=>%-10s Joined path is=>%s"%(x,z,os.path.join(x,z))

x='n:/'
print  "X=>%-20s z=>%-10s Joined path is=>%s"%(x,z,os.path.join(x,z))

x='m:/billdeeg.scons1'
print  "X=>%-20s z=>%-10s Joined path is=>%s"%(x,z,os.path.join(x,z))



When I run it I get the following output:
C:\cygwin\home\billdeeg\tmp>python try_ospathjoin.py
X=>m:/billdeeg.scons1   z=>/build     Joined path is=>/build
X=>m:/billdeeg.scons1/  z=>/build     Joined path is=>/build
X=>m:/billdeeg.scons1   z=>/build     Joined path is=>/build
X=>m:/billdeeg.scons1   z=>build      Joined path is=>m:/billdeeg.scons1\build
X=>n:                   z=>/build     Joined path is=>n:/build
X=>n:/                  z=>/build     Joined path is=>n:/build
X=>m:/billdeeg.scons1   z=>/build     Joined path is=>/build


I would expect in all cases that I would get :
n:/build or m:/billdeeg.scons1/build
But as you can see in some cases that's not what I get.

Here's the docs about os.path.join:
join( path1[, path2[, ...]])

Join one or more path components intelligently. If any component is an
absolute path, all previous components (on Windows, including the
previous drive letter, if there was one) are thrown away, and joining
continues. The return value is the concatenation of path1, and
optionally path2, etc., with exactly one directory separator (os.sep)
inserted between components, unless path2 is empty. Note that on
Windows, since there is a current directory for each drive,
os.path.join("c:", "foo") represents a path relative to the current
directory on drive C: (c:foo), not c:\\foo.

I'm guessing I get : /build in because of the clause above about "if
any component is an absolute path...", is that correct?

So to get what I expect, looks like I need to insure that none of the
[1:] arguments start with a '/' or '\' ?

Thanks,
Bill


More information about the Baypiggies mailing list