newbiez newbiez - 2 years ago 127
Python Question

Tell python to access resources above the path of the script

If you run a script from /tmp/myfolder/myscript/, and want to access a resource in myfolder, how do you do that in python?

I did get the file path with

, (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.

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.

Answer Source

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

import os

This will change your working directory to the one above the current one (just like cd ..).

You can also use .. for many operations that use paths. For example, if you want to open a file that is up one directory: open('../myfile.txt'), etc. You may also find the answers to this question useful, depending on what your goal is.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download