umläute umläute - 1 year ago 90
Python Question

constructing absolute path with os.path.join()

I'd like to construct an absolute path in python, while at the same time staying fairly oblivious of things like path-separator.

edit0: for instance there is a directory on the root of my filesystem

on w32), and I want to construct this only from the elements
(on w32, I probably also need a disk-ID, like

In order to not having to worry about path-separators,
is obviously the tool of choice. But it seems that this will only ever create relative paths:

print "MYPATH:", os.path.join('etc', 'init.d')
MYPATH: etc/init.d

Adding a dummy first-element (e.g.
) doesn't help anything:

print "MYPATH:", os.path.join('', 'etc', 'init.d')
MYPATH: etc/init.d

Making the first element absolute obviously helps, but this kind of defeats the idea of using

print "MYPATH:", os.path.join('/etc', 'init.d')
MYPATH: /etc/init.d

edit1: using
will only try to convert a relative path into an absolute path.
e.g. consider running the following in the working directory

print "MYPATH:", os.path.abspath(os.path.join('etc', 'init.d'))
MYPATH: /home/foo/etc/init.d

So, what is the standard cross-platform way to "root" a path?

root = ??? # <--
print "MYPATH:", os.path.join(root, 'etc', 'init.d')
MYPATH: /etc/init.d

edit2: the question really boils down to: since the trailing slash in
makes this path an absolute path, is there a way to construct this trailing slash programmatically?
(I do not want to make assumptions that a trailing slash indicates an absolute path)

Answer Source

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:
  while 1:
    if not folder:
  return drive+path

 os.path.join(getRoot(), 'etc', 'init.d')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download