Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is a bit tricky. For instance, the following code:</p> <pre><code>import sys import os z = sys.argv[0] p = os.path.dirname(z) f = os.path.abspath(p) print "argv[0]={0} , dirname={1} , abspath={2}\n".format(z,p,f) </code></pre> <p>gives this output on Windows</p> <p><code>argv[0]=../zzz.py , dirname=.. , abspath=C:\Users\michael\Downloads</code> First of all, notice that argv has the slash which I typed in the command <code>python ../zzz.py</code> and the absolute path has the normal Windows backslashes. If you need to be cross platform you should probably refrain from putting regular slashes on Python command lines, and use <code>os.sep</code> to refer to the character that separated pathname components.</p> <p>So far I have only partly answered your question. There are a couple of ways to use the value of <code>f</code> to get what you want. Brute force is to use something like:</p> <pre><code>targetpath = f + os.sep + ".." + os.sep + ".." </code></pre> <p>which would result in something like <code>C:\Users\michael\Downloads\..\..</code> on Windows and <code>/home/michael/../..</code> on Unix. Each .. goes back one step and is the equivalent of removing the pathname component.</p> <p>But you could do better by breaking up the path:</p> <pre><code>target = f.split(os.sep) targetpath = os.sep.join(target[:-2] </code></pre> <p>and rejoining all but the last two bits to get <code>C:\Users</code> on Windows and <code>/</code> on Unix. If you do that it might be a good idea to check that there are enough pathname components to remove.</p> <p>Note that I ran the program above by typing <code>python ../xxx.py</code>. In other words I was not in the same working directory as the script, therefore getcwd() would not be useful.</p>
    singulars
    1. This table or related slice is empty.
    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.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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