Skip to content

#97: Changing the Current Working Directory

When you use a Python script to automate things, you may not always want to stay in the directory you run your script from. Let us look how we can change the current working directory and save a lot of typing.

Get the current working directory

The current working directory is a basic UNIX concept that impacts the commands you run in the console. Most commands run in the current working directory if you do not specify a path. If you set the current working directory to the one you want to work with, you can save all the extra paths and have a lot less to type.

You can use the Python function os.getcwd() to get the current working directory:

1
2
3
4
5
6
import os

current = os.getcwd()

print(current)
#-> D:\Python\PythonFriday\helper

In the command line you can use the command pwd to get the same information.

Change the current working directory

We can change the current working directory with the os.chdir() function to the new path we pass as an argument:

1
2
3
4
5
6
os.chdir('C:\Temp')

new_dir = os.getcwd()

print(new_dir)
#-> C:\Temp

In the command line you would use cd path to make the same change.

Conclusion

The current working directory is an easy to overlook concept. If you know that it exist and how you can change it, you can save a lot of typing.