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?
Asked
Active
Viewed 1,491 times
1
-
I am not sure what you are asking exactly. `os.chdir('../../')` will bring you back two directories. This will change your working directory. – elethan Sep 29 '16 at 17:36
-
the py script I'm running on the terminal is not changing the directory in the terminal – JTheboss Sep 29 '16 at 17:40
-
`os.chdir` will not change the directory you are in in the terminal, it will only change it for the context inside the script. Why do you want to change it in the terminal? – elethan Sep 29 '16 at 17:41
-
I need automated utility for users. – JTheboss Sep 29 '16 at 17:45
-
If all the operations you are doing are in python, it doesn't matter that the directory doesn't change in the terminal, since it *will* change the working directory as far as Python is concerned. – elethan Sep 29 '16 at 17:47
-
So changing terminal directory is not possible in Python? – JTheboss Sep 29 '16 at 17:49
-
I am looking into it now, but I have not found a way to do so yet. I will update my answer if I figure out definitively whether it is possible or not. – elethan Sep 29 '16 at 17:53
-
I have asked the following question: http://stackoverflow.com/q/39777348/3642398. I will update my answer if I learn anything from it that might help you. – elethan Sep 29 '16 at 18:25
1 Answers
1
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:
os.getcwd()
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.
Edit:
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
.

elethan
- 16,408
- 8
- 64
- 87