cd is the shell command to change the working directory.
How do I change the current working directory in Python?
cd is the shell command to change the working directory.
How do I change the current working directory in Python?
You can change the working directory with:
import os
os.chdir(path)
There are two best practices to follow when using this method:
Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use os.chdir() to change the CWD of the calling process.
I would use os.chdir like this:
os.chdir("/path/to/change/to")
By the way, if you need to figure out your current path, use os.getcwd().
More here
If you're using a relatively new version of Python, you can also use a context manager, such as this one:
from __future__ import with_statement
from grizzled.os import working_directory
with working_directory(path_to_directory):
# code in here occurs within the directory
# code here is in the original directory
UPDATE
If you prefer to roll your own:
import os
from contextlib import contextmanager
@contextmanager
def working_directory(directory):
owd = os.getcwd()
try:
os.chdir(directory)
yield directory
finally:
os.chdir(owd)
import os
abs_path = 'C://a/b/c'
rel_path = './folder'
os.chdir(abs_path)
os.chdir(rel_path)
You can use both with os.chdir(abs_path) or os.chdir(rel_path), there's no need to call os.getcwd() to use a relative path.
If You would like to perform something like "cd.." option, just type:
os.chdir("..")
it is the same as in Windows cmd: cd.. Of course import os is neccessary (e.g type it as 1st line of your code)
The Path objects in path library offer both a context manager and a chdir method for this purpose:
from path import Path
with Path("somewhere"):
...
Path("somewhere").chdir()
If you use spyder and love GUI, you can simply click on the folder button on the upper right corner of your screen and navigate through folders/directories you want as current directory. After doing so you can go to the file explorer tab of the window in spyder IDE and you can see all the files/folders present there. to check your current working directory go to the console of spyder IDE and simply type
pwd
it will print the same path as you have selected before.