The OS module is a standard Python utility that allows you to interact with the underlying operating system. With the Python OS module you can list all files and folders in a directory, create new files and folders, open files and more. In this tutorial, we’ll introduce the Python OS module by demonstrating how to set your current working directory using the Python chdir and getcwd methods.

During our series on the OS module, we’ll be using the following directory structure:

raw image

Getting and Setting the Current Working Directory

To get the current working directory for your Python script, use the getcwd() method. You’ll need to import the OS module in your script before you call the getcwd() method. This is a simple step that requires adding the import os command to your Python script.

The following script prints the current working directory for your Python script.

import os
wd = os.getcwd()
print(wd)

You can see the current working directory in the output. In our example, we get this path:

Output:

C:\main directory

By default, the getcwd command returns the path where your Python script is stored. You can change the current working directory using the chdir() method from the OS module, like this:

os.chdir(r"C:\main directory\documents")

Now if you again print your current working directory via the getcwd() method after changing the directory using chdir(), you’ll see the updated path.

import os
os.chdir(r"C:\main directory\documents")
wd = os.getcwd()
print(wd)

Output:

C:\main directory\documents

Our next tutorial will assume we’re back in our original current working directory, C:\main directory, so let’s change our directory back to what it was originally. Here’s the full script for doing that:

import os
os.chdir(r"C:\main directory")
wd = os.getcwd()

That’s all there is to getting, setting and changing your current working directory with the Python OS module. The getcwd and chdir methods are quite intuitive and it’s critical you commit them to memory if you’re frequently working with files and folders using Python. Our next tutorial shows you how to use the Python OS Module to list all files and folders in a directory, which is a fantastic skill for file manipulation and processing. Make sure you check it out and subscribe using the form below for more Python OS tips.


Code More, Distract Less: Support Our Ad-Free Site

You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.