When I enter the following into my terminal shell, my current working directory won't change. I don't get any error codes.
import os
os.chdir('/Users/*myname*/Documents')
When I exit the shell and enter "pwd" in the terminal, I keep getting /Users/*myname*
. It won't change the current working directory to Documents
. Can someone help me with this?
CodePudding user response:
Every process has its own "current working directory". os.chdir
changes the current working directory of the python process executing it:
>>> import os
>>> os.getcwd()
'/'
>>> os.chdir('/tmp')
>>> os.getcwd()
'/tmp'
Once you exit the python process and return to the shell process that spawned it. the working directory of that process won't be affected.
CodePudding user response:
This is not how chdir
works.
Any command you give using os
module works within Python context and not the terminal context.
Ex - You open a terminal in /Users/abc
and then run a python interpreter there, you will get a working directory within that python interpreter and now if you make any changes in current path it will work but within that python context and it wont affect where your terminal was open.
Try this - after changing to a directory, make a file using python
and you will get the file where you chdir
.
CodePudding user response:
You can imagine the python shell as a separate process. Once you are into that shell you are transferred into "another terminal" where you can programmatically interact with the file system using a library like os
.
You can try listing all the files inside the current directory after changing directory to verify the change. Insert os.listdir()
just after os.chdir('/Users/myname/Documents')
.
However, once you exit the python shell you are back to the previous shell process where you started. There, the current working directory hasn't changed.