Note that there are some explanatory texts on larger screens.

plurals
  1. POconstructing absolute path with os.path.join()
    primarykey
    data
    text
    <p>I'd like to construct an absolute path in python, while at the same time staying fairly oblivious of things like path-separator.</p> <p><strong>edit0:</strong> for instance there is a directory on the root of my filesystem <code>/etc/init.d</code> (or <code>C:\etc\init.d</code> on w32), and I want to construct this only from the elements <code>etc</code> and <code>init.d</code> (on w32, I probably also need a disk-ID, like <code>C:</code>)</p> <p>In order to not having to worry about path-separators, <code>os.join.path()</code> is obviously the tool of choice. But it seems that this will only ever create <em>relative</em> paths:</p> <pre><code> print "MYPATH:", os.path.join('etc', 'init.d') MYPATH: etc/init.d </code></pre> <p>Adding a dummy first-element (e.g. <code>''</code>) doesn't help anything:</p> <pre><code> print "MYPATH:", os.path.join('', 'etc', 'init.d') MYPATH: etc/init.d </code></pre> <p>Making the first element absolute obviously helps, but this kind of defeats the idea of using <code>os.path.join()</code></p> <pre><code> print "MYPATH:", os.path.join('/etc', 'init.d') MYPATH: /etc/init.d </code></pre> <p><strong>edit1:</strong> using <code>os.path.abspath()</code> will only try to convert a relative path into an absolute path. e.g. consider running the following in the working directory <code>/home/foo</code>:</p> <pre><code> print "MYPATH:", os.path.abspath(os.path.join('etc', 'init.d')) MYPATH: /home/foo/etc/init.d </code></pre> <p>So, what is the standard cross-platform way to "root" a path?</p> <pre><code> root = ??? # &lt;-- print "MYPATH:", os.path.join(root, 'etc', 'init.d') MYPATH: /etc/init.d </code></pre> <p><strong>edit2:</strong> the question really boils down to: since the leading slash in <code>/etc/init.d</code> makes this path an absolute path, is there a way to construct this leading slash programmatically? (I do not want to make assumptions that a leading slash indicates an absolute path)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload