Home » Python Directories Tutorial with Examples

Python Directories Tutorial with Examples

In Python, working with directories (folders) is essential for managing files and organizing data. Python provides several built-in modules and functions to create, modify, and navigate directories.

One of the most common modules used for this purpose is the os module, along with os.path and pathlib modules.

In this tutorial, we will cover:

  1. What is a Directory in Python?
  2. Creating Directories
  3. Changing the Current Working Directory
  4. Listing Files in a Directory
  5. Checking if a Directory Exists
  6. Removing Directories
  7. Working with Paths Using os.path and pathlib
  8. Examples and Use Cases

Let’s dive into each topic with examples and explanations.

1. What is a Directory in Python?

A directory (or folder) is a file system structure that can contain files and other directories. Python provides several functions to work with directories, allowing you to:

  • Create directories for organizing files.
  • Navigate through directories and change the current working directory.
  • List files and subdirectories within a directory.
  • Check for directory existence and remove directories.

We’ll primarily use the os module and pathlib for working with directories.

2. Creating Directories

You can create a new directory using the os.mkdir() function or pathlib.Path.mkdir() method.

Example 1: Creating a Directory Using os.mkdir()

import os

# Creating a new directory
directory_name = "new_folder"
os.mkdir(directory_name)

print(f"Directory '{directory_name}' created successfully!")

Output:

Directory 'new_folder' created successfully!
  • In this example, os.mkdir() creates a new directory called “new_folder” in the current working directory.

Example 2: Creating a Directory Using pathlib

from pathlib import Path

# Creating a new directory using pathlib
directory = Path("new_folder_pathlib")
directory.mkdir()

print(f"Directory '{directory}' created successfully using pathlib!")

Output:

Directory 'new_folder_pathlib' created successfully using pathlib!
  • The Path.mkdir() method from the pathlib module creates a directory, and the advantage of pathlib is that it provides an object-oriented approach to handling file paths.

3. Changing the Current Working Directory

You can change the current working directory using the os.chdir() function. This function allows you to navigate between directories in your file system.

Example: Changing the Working Directory

import os

# Changing to a different directory
new_directory = "/path/to/directory"
os.chdir(new_directory)

# Printing the current working directory
current_directory = os.getcwd()
print(f"Current working directory: {current_directory}")

Output:

Current working directory: /path/to/directory
  • In this example, os.chdir() changes the current working directory, and os.getcwd() returns the current directory after the change.

4. Listing Files in a Directory

To list all the files and directories in a given directory, you can use os.listdir() or pathlib.Path.iterdir().

Example 1: Listing Files Using os.listdir()

import os

# Listing all files and directories in the current directory
current_directory = os.getcwd()
items = os.listdir(current_directory)

print(f"Items in '{current_directory}':")
for item in items:
    print(item)

Output:

Items in '/path/to/current/directory':
file1.txt
file2.txt
subfolder
  • In this example, os.listdir() returns a list of all files and directories in the current directory.

Example 2: Listing Files Using pathlib.Path.iterdir()

from pathlib import Path

# Listing all files and directories using pathlib
current_directory = Path(".")
for item in current_directory.iterdir():
    print(item)

Output:

file1.txt
file2.txt
subfolder
  • The Path.iterdir() method provides an iterator that returns all files and directories in the current directory.

5. Checking if a Directory Exists

Before creating or accessing a directory, it’s a good practice to check if it exists. You can use os.path.exists() or pathlib.Path.exists() to do this.

Example 1: Checking Directory Existence with os.path.exists()

import os

directory_name = "new_folder"

# Checking if the directory exists
if os.path.exists(directory_name):
    print(f"Directory '{directory_name}' exists.")
else:
    print(f"Directory '{directory_name}' does not exist.")

Output:

Directory 'new_folder' exists.
  • In this example, os.path.exists() checks if the directory exists.

Example 2: Checking Directory Existence with pathlib

from pathlib import Path

directory = Path("new_folder_pathlib")

# Checking if the directory exists using pathlib
if directory.exists():
    print(f"Directory '{directory}' exists.")
else:
    print(f"Directory '{directory}' does not exist.")

Output:

Directory 'new_folder_pathlib' exists.
  • The Path.exists() method is used to check if a directory exists.

6. Removing Directories

You can remove an empty directory using os.rmdir() or pathlib.Path.rmdir(). If the directory contains files, you need to delete those first or use additional methods to remove everything.

Example 1: Removing a Directory Using os.rmdir()

import os

# Removing an empty directory
directory_name = "new_folder"

if os.path.exists(directory_name):
    os.rmdir(directory_name)
    print(f"Directory '{directory_name}' removed successfully!")
else:
    print(f"Directory '{directory_name}' does not exist.")

Output:

Directory 'new_folder' removed successfully!
  • In this example, os.rmdir() removes the directory if it exists.

Example 2: Removing a Directory Using pathlib

from pathlib import Path

directory = Path("new_folder_pathlib")

# Removing an empty directory using pathlib
if directory.exists():
    directory.rmdir()
    print(f"Directory '{directory}' removed successfully!")
else:
    print(f"Directory '{directory}' does not exist.")

Output:

Directory 'new_folder_pathlib' removed successfully!
  • The Path.rmdir() method removes the directory if it exists.

7. Working with Paths Using os.path and pathlib

The os.path module and pathlib provide functions to work with file and directory paths. These modules can help you:

  • Join paths to navigate directories.
  • Split paths into directory and filename components.
  • Get the absolute path of files or directories.

Example 1: Joining Paths with os.path.join()

import os

# Joining paths
directory = "/path/to"
file_name = "file.txt"

full_path = os.path.join(directory, file_name)
print(f"Full path: {full_path}")

Output:

Full path: /path/to/file.txt
  • In this example, os.path.join() joins the directory and file name into a full path.

Example 2: Joining Paths with pathlib

from pathlib import Path

# Joining paths using pathlib
directory = Path("/path/to")
file_name = "file.txt"

full_path = directory / file_name
print(f"Full path: {full_path}")

Output:

Full path: /path/to/file.txt
  • In this example, the / operator in pathlib joins the directory and file name into a path.

Example 3: Getting the Absolute Path with os.path.abspath()

import os

# Getting the absolute path
relative_path = "file.txt"
absolute_path = os.path.abspath(relative_path)

print(f"Absolute path: {absolute_path}")

Output:

Absolute path: /path/to/current/directory/file.txt
  • The os.path.abspath() function returns the absolute path of a given file or directory.

Example 4: Getting the Absolute Path with pathlib

from pathlib import Path

# Getting the absolute path using pathlib
file = Path("file.txt")
absolute_path = file.resolve()

print(f"Absolute path: {absolute_path}")

Output:

Absolute path: /path/to/current/directory/file.txt
  • The Path.resolve() method returns the absolute path of the file or directory.

8. Examples and Use Cases

Example 1: Create a Directory if It Doesn’t Exist

import os

directory_name = "new_directory"

# Check if the directory exists, and create it if not
if not os.path.exists(directory_name):
    os.mkdir(directory_name)
    print(f"Directory '{directory_name}' created.")
else:
    print(f"Directory '{directory_name}' already exists.")

Output:

Directory 'new_directory' created.
  • In

this example, the script checks if the directory exists before creating it.

Example 2: List All Files in a Directory and Subdirectories

import os

# Walk through all files and directories
for dirpath, dirnames, filenames in os.walk("."):
    print(f"Found directory: {dirpath}")
    for filename in filenames:
        print(f"  {filename}")

Output:

Found directory: .
  file1.txt
  file2.txt
Found directory: ./subfolder
  file3.txt
  • In this example, os.walk() is used to recursively list all files and directories starting from the current directory.

Summary of Python Directory Operations:

Function Description Example
os.mkdir() Creates a new directory. os.mkdir(“folder”)
Path.mkdir() Creates a new directory using pathlib. Path(“folder”).mkdir()
os.chdir() Changes the current working directory. os.chdir(“/path/to/directory”)
os.listdir() Lists all files and directories in a directory. os.listdir(“.”)
Path.iterdir() Lists all files and directories using pathlib. Path(“.”).iterdir()
os.path.exists() Checks if a directory exists. os.path.exists(“folder”)
Path.exists() Checks if a directory exists using pathlib. Path(“folder”).exists()
os.rmdir() Removes an empty directory. os.rmdir(“folder”)
Path.rmdir() Removes an empty directory using pathlib. Path(“folder”).rmdir()
os.path.join() Joins multiple path components. os.path.join(“/path”, “file.txt”)
Path.resolve() Gets the absolute path using pathlib. Path(“file.txt”).resolve()

Conclusion

Python provides powerful tools for working with directories using the os module and pathlib. In this tutorial, we covered:

  • How to create directories using os.mkdir() and pathlib.
  • Changing the current directory, listing files, and checking directory existence.
  • Removing directories and working with paths using os.path and pathlib.
  • Practical examples for common directory operations.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More