constructing absolute path with os.path.join() constructing absolute path with os.path.join() python python

constructing absolute path with os.path.join()


Using os.sep as root worked for me:

path.join(os.sep, 'python', 'bin')

Linux: /python/bin

Windows: \python\bin

Adding path.abspath() to the mix will give you drive letters on Windows as well and is still compatible with Linux:

path.abspath(path.join(os.sep, 'python', 'bin'))

Linux: /python/bin

Windows: C:\python\bin


I think you can use os.path.normpath. Here's what I get on Windows:

>>> os.path.normpath("/etc/init.d")'\\etc\\init.d'

I'm not sure exactly what the right thing to do with the drive prefix is, but I think leaving it off means something like "keep using the drive I'm on now," which is probably what you want. Maybe someone more familiar with Windows can clarify?


so the solution i came up with, is to construct the root of the filesystem by following a given file to it's root:

def getRoot(file=None):  if file is None:      file='.'  me=os.path.abspath(file)  drive,path=os.path.splitdrive(me)  while 1:    path,folder=os.path.split(path)    if not folder:       break  return drive+path os.path.join(getRoot(), 'etc', 'init.d')