JTheboss JTheboss - 3 months ago 26
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?


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.