How to Change Directories in Python



Python


In this article, we show how to change directories in Python (change the current working directory to another directory).

Say, for example, you are current working in a directory, such as, C:\\Users\\David\\Projects1, and you want to change it to, C:\\Users\\David\\Projects2.

Let's say, you want to change from the Projects1 directory to the Projects2 directory.

With Python, you can easily change the current working directory to any other current existing directory on the computer using built-in functions of Python.

The line of code to do so is, os.chdir(directory_to_change_to).

The full line of code to do so is shown below.



First, in our code, we import the os module.

After this, we change the directory from the current directory (whatever directory it is) to the new directory we specify, which is, C:\\Users\\David\\Projects2

As long as the directory that you want to change to exists, the current working directory is now changed to the directory you specify.

If the directory does not exist, an error will be thrown. You will get an error that states, FileNotFoundError: [WinError 2] The system cannot find the file specified.

To now check that the directory has been changed, we can run the following code, which gives us the output shown below.



So, you can now see that the directory has been changed and the current working directory is what we changed the directory to.

So, this is how you can change the current working directory in Python.


Related Resources



HTML Comment Box is loading comments...