JTheboss JTheboss - 1 year ago 96
Python Question

How to go one or more levels using os.chdir with '..''s as arguments

How do I change path in Python using '..' to go down one or more levels as argument to os.chdir(). So that if I am on /home/usr/one and I want to go to 'home' directory a '../..' argument to chdir will do it. Do I wrap the argument in some other function?

Answer Source

As you say in your question, if you are in the directory /home/usr/one os.chdir('../../') will bring you to /home/.

You can confirm this by calling:


Before and after changing directories. This function will show you the current working directory. Also, there is no need to wrap the argument to chdir() in another function.


Note that os.chdir() in a script will not change the directory you are in when you run the script from the terminal. In other words, if you are in /home/usr/one and run a script with python myscript.py, any directory changes made with os.chdir() within that script will not be refelected when the script finishes; you will still be in /home/usr/one.

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