Python Friday #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.

This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.

 

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:

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:

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.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.