In this article we will discuss how to change the current working directory in python.
Current working directory is the directory in which program is running.
Change Current Working Directory in Python
First of all we need to import python’s os module i.e.
import os
Python’s os module provides a function to change the current working directory i.e.
Frequently Asked:
os.chdir(path)
It changes the current working directory to the given path.
Let’s understand by an example,
First print the current working directory using os.getcwd() i.e.
print("Current Working Directory " , os.getcwd())
Now let’s change the current working directory using os.chdir(path) i.e.
Latest Python - Video Tutorial
os.chdir("/home/varun/temp")
If the given path don’t exist then os.chdir() with throw error : FileNotFoundError. Therefore we should either call it using try / except i.e.
try: # Change the current working Directory os.chdir("/home/varun/temp") print("Directory changed") except OSError: print("Can't change the Current Working Directory")
or check if the new directory exists before changing the working directory i.e.
# Check if New path exists if os.path.exists("/home/varun/temp") : # Change the current working Directory os.chdir("/home/varun/temp") else: print("Can't change the Current Working Directory")
Complete example is as follows,
import os def main(): print("Current Working Directory " , os.getcwd()) try: # Change the current working Directory os.chdir("/home/varun/temp") print("Directory changed") except OSError: print("Can't change the Current Working Directory") print("Current Working Directory " , os.getcwd()) # Check if New path exists if os.path.exists("/home/varun/temp") : # Change the current working Directory os.chdir("/home/varun/temp") else: print("Can't change the Current Working Directory") print("Current Working Directory " , os.getcwd()) if __name__ == '__main__': main()
Output:
Current Working Directory /home/varun/Documents/blog/pythonSamples/FileSamples Directory changed Current Working Directory /home/varun/temp Current Working Directory /home/varun/temp
Hi, it didn’t work. Would you help me?
I got the error message below:
—————————————————————————
NameError Traceback (most recent call last)
in
—-> 1 print(“Current Working Directory ” , os.getcwd())
NameError: name ‘os’ is not defined
This error is because you have not imported the os module before using that. You can import the os module as follows,
import os
You can copy the complete example in above code and try, it will work.
I have also updated the import os step in article.
Thanks