Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to change directory in Python

Getting Around: Changing Directories in Python

Why Change Directory?

Before we delve into the intricacies of directory navigation in Python, let's first understand why we need to change directories. Imagine your computer as a massive library and directories as shelves in that library. Each shelf (directory) holds different kinds of books (files). As a librarian (programmer), you need to know how to navigate these shelves to find, use, or rearrange the books you need. In Python, we often need to change directories to access different files or datasets that are not in our current working directory.

Understanding Your Current Location

When you start Python, you are in the 'current working directory'. This is like standing in front of a particular bookshelf in the library. This is where Python will look for any files you ask it to open. To see where you currently are, we use the os module, which allows us to interact with the underlying operating system.

Here's a simple code snippet:

import os

print(os.getcwd())

Running this code will print your current working directory.

Changing Your Directory: The os.chdir() Function

Now, let's say we want to move to a different bookshelf (directory). We'll use the os.chdir() function. It's like telling the librarian (Python) to move to a different shelf.

Here's an example:

import os

os.chdir('/path/to/your/directory')

Just replace '/path/to/your/directory' with the path of the directory you want to navigate to.

A Note on Paths

When specifying paths in Python, there are two types you could use: relative paths and absolute paths.

Absolute Paths

An absolute path is like giving the librarian detailed instructions to find a bookshelf, starting from the library entrance. It's a path that starts from a root directory to the directory we're interested in. In most systems, it starts with a slash '/'.

Here's how you'd use an absolute path with os.chdir():

os.chdir('/Users/username/Documents/project_folder')

Relative Paths

A relative path, on the other hand, is like telling the librarian where to go based on their current location. For example, "move two shelves to the right". In Python, we use dot notation for this.

  • Single dot '.' represents the current directory.
  • Double dots '..' represents the parent directory (one directory up).

Here's how you'd use a relative path with os.chdir():

os.chdir('../project_folder')

This code tells Python to move one directory up and then go into the 'project_folder'.

Confirming Your Move

To confirm that you've moved to the right directory, you can again use os.getcwd(). It's like asking the librarian, "Are we at the right shelf now?"

print(os.getcwd())

This will print the new current working directory, and you can check if it's the directory you wanted to move to.

Be Aware of Errors

Sometimes, the path you want to navigate to does not exist. In such cases, Python will raise a FileNotFoundError. It's like telling the librarian to move to a bookshelf that doesn't exist. The librarian will be confused and tell you, "I can't find that shelf."

Here's an example:

try:
    os.chdir('/path/that/does/not/exist')
except FileNotFoundError:
    print("The directory does not exist")

In this code, we're trying to handle the error gracefully using a try-except block. If the directory does not exist, Python will print "The directory does not exist" instead of throwing an error and stopping the program.

Conclusion: The Power of Navigation

Mastering directory navigation in Python is like learning how to find any book in a massive library. It may seem overwhelming at first, but once you get the hang of it, it becomes second nature. The power to swiftly navigate through directories allows you to manipulate and access files efficiently, making your Python journey smoother and more enjoyable. Just like how a librarian feels when they can locate any book in their vast library with ease, you too will feel a sense of accomplishment as you master the art of changing directories in Python. Happy navigating!