Back to Python
2026-03-225 min read

Changing Directory in Python

Learn Changing Directory in Python step by step with clear examples and exercises.

Title: Changing Directory in Python: A full guide

Why This Matters

Navigating directories is a fundamental skill for any programmer. Understanding how to change directories using Python can help you manage your projects more efficiently, making it easier to find and organize files. Additionally, this knowledge is crucial for automating tasks, such as scripting file backups or data processing pipelines.

Apart from the practical benefits, learning how to change directories in Python also helps you understand the file system structure and improve your problem-solving skills by working with different paths and directory manipulations.

Prerequisites

To understand changing directories in Python, you should have a basic understanding of:

  1. Python syntax and variables
  2. Basic file operations (reading and writing)
  3. Understanding the concept of directories and files
  4. Familiarity with string manipulation, especially path manipulation
  5. Knowledge of exceptions in Python
  6. Basic understanding of the os module and its functions

Core Concept

In Python, you can change directories using the os module's chdir() function. This function takes a single argument—the path to the directory you want to navigate to.

import os

Change current working directory to 'new_directory'

os.chdir('new_directory')


To check the current working directory, use `os.getcwd()`.

current_directory = os.getcwd()

print(current_directory)


### Directory Paths

When specifying a directory path, you can use both absolute and relative paths. An absolute path starts from the root directory (`/`) while a relative path is based on the current working directory.

For example:

- Absolute path: `'/home/user/projects/my_project'`
- Relative path (if the current directory is `'/home/user/projects'): 'my_project'`

### Navigating Up a Directory Level

To navigate up one level in the directory hierarchy, you can use `os.path.normpath(os.path.join(current_directory, '..'))`.

parent_directory = os.path.normpath(os.path.join(current_directory, '..'))

print(parent_directory)


### Creating and Checking Directories

To check if a directory exists, use `os.path.exists()`.

if os.path.exists('my_directory'):

print("Directory my_directory exists.")

else:

print("Directory my_directory does not exist.")


You can also create a new directory using `os.mkdir()`. If the directory already exists, an error will be raised. To handle this situation, use a try-except block.

import os

new_directory = '/home/user/new_directory'

if not os.path.exists(new_directory):

os.mkdir(new_directory)

else:

print("Directory already exists.")

Worked Example

Let's say you have a project named "my_project" in a directory called "personal_projects." To navigate to that directory, follow these steps:

  1. Import the os module.
  2. Use os.path.abspath(os.path.join('..', 'personal_projects')) to find the absolute path of the "personal_projects" directory from the current working directory.
  3. Change the current working directory to "personal_projects".
  4. Use os.chdir('my_project') to move into "my_project" directory.
import os

Find absolute path of personal_projects directory

personal_directory = os.path.abspath(os.path.join('..', 'personal_projects'))

Change to personal_projects directory

os.chdir(personal_directory)

Now change to my_project directory

os.chdir('my_project')

Common Mistakes

  1. Not importing the os module: Always remember to import os before using its functions.
  1. Incorrect path syntax: Make sure your paths are written correctly, and use either absolute or relative paths depending on your needs.
  1. Not checking the current working directory: After changing directories, it's a good practice to verify that you have navigated to the correct one using os.getcwd().
  1. Raised error when trying to navigate to non-existing directories: You can use a try-except block to handle this situation:
import os

try:
os.chdir('non_existing_directory')
except FileNotFoundError:
print("The specified directory does not exist.")
  1. Not handling exceptions when dealing with paths: Be aware of potential errors such as FileNotFoundError, IsADirectoryError, and NotADirectoryError.
  1. Using the wrong function to create a new directory: If you want to create a new directory and its parent directories if they do not exist, use os.makedirs() instead of os.mkdir().

Practice Questions

  1. Write a script that changes the current working directory to the user's home directory (e.g., "/home/user").
import os
home_directory = os.path.expanduser('~')
os.chdir(home_directory)
  1. Given the following directories: /home/user/projects/my_project, write a script that navigates to the "my_project" directory from any parent directory.
import os

Find absolute path of my_project directory

project_directory = os.path.abspath(os.path.join('..', 'projects', 'my_project'))

Change to my_project directory

os.chdir(project_directory)


3. Write a script that changes the current working directory to a subdirectory named "subfolder" within the "personal_projects" directory (e.g., `/home/user/personal_projects/subfolder`).

import os

Find absolute path of personal_projects directory

personal_directory = os.path.abspath(os.path.join('..', 'personal_projects'))

Change to personal_projects directory

os.chdir(personal_directory)

Now change to subfolder directory

os.chdir('subfolder')


4. Write a script that lists all directories in the current working directory and prints them out.

import os

for item in os.listdir(current_directory):

if os.path.isdir(os.path.join(current_directory, item)):

print(item)


5. Write a script that creates a new directory named "new_project" under the current working directory and changes to it.

import os

Create new_project directory if it does not exist

if not os.path.exists('new_project'):

os.mkdir('new_project')

Change to new_project directory

os.chdir('new_project')

FAQ

  1. How can I navigate up one level in the directory hierarchy?

Use os.path.normpath(os.path.join(current_directory, '..')).

  1. What happens if the specified directory does not exist?

If the directory does not exist, an error will be raised. You can use a try-except block to handle this situation:

import os

try:
os.chdir('non_existing_directory')
except FileNotFoundError:
print("The specified directory does not exist.")
  1. How can I list all directories in the current working directory?

Use os.listdir() and filter out files by checking their extension (e.g., '.txt', '.py').

import os

for item in os.listdir(current_directory):
if os.path.isdir(os.path.join(current_directory, item)):
print(item)
  1. How can I find the parent directory of a given directory?

Use os.path.dirname(path).

import os
parent_directory = os.path.dirname('/home/user/personal_projects')
print(parent_directory)
  1. How can I create a new directory if it does not exist?

Use os.makedirs() to create a new directory and all necessary parent directories if they do not exist.

import os

new_directory = '/home/user/new_directory'
if not os.path.exists(new_directory):
os.makedirs(new_directory)
  1. How can I check if a directory is empty?

Use os.listdir() and count the number of items in the directory. If the count is 0, the directory is empty.

import os
if len(os.listdir(directory)) == 0:
print("The directory is empty.")
else:
print("The directory is not empty.")
  1. How can I remove a directory and its contents?

To remove a directory and all of its contents, use shutil.rmtree().

import shutil
shutil.rmtree('/path/to/directory')
Changing Directory in Python | Python | XQA Learn