Tell python to access resources above the path of the script
<p>If you run a script from /tmp/myfolder/myscript/, and want to access a resource in myfolder, how do you do that in python?</p>

<p>I did get the file path with <code>__file__</code>, (I was told to not use it because it may not always be populated) but I can't do like in bash, where I "cd .."  to get to the previous directory, because Python does not understand that.</p>

<p>I would like to run the python script and no matter where the folder is, it will always go up one level and get the resource that I need.</p>

<p>Python does understand <code>cd</code>: <code>os.chdir()</code>. I am not sure exactly what you are trying to do, but you can try:</p>

<pre><code>import os
os.chdir('..')
</code></pre>

<p>This will change your working directory to the one above the current one (just like <code>cd ..</code>).</p>

<p>You can also use <code>..</code> for many operations that use paths. For example, if you want to open a file that is up one directory: <code>open('../myfile.txt')</code>, etc. You may also find the answers to <a href="http://stackoverflow.com/questions/21030751/python-imports-from-the-directory-above">this question</a> useful, depending on what your goal is.</p>

python