Skip to content
Home » directories in Python

directories in Python

Here is a clear, complete, and exam-oriented explanation of Directories in Python.
This covers: creating, listing, changing, removing directories, and related functions.


Directories in Python

A directory is a folder on your computer that stores files and subfolders.
Python provides powerful functions to work with directories using the os and os.path modules.

Directory operations include:

✔ Creating directories
✔ Removing directories
✔ Changing current directory
✔ Listing files and folders
✔ Checking directory existence
✔ Working with paths


—————————————–

1. Importing Required Module

import os

—————————————–

2. Get Current Working Directory

Use os.getcwd() to know the current working folder.

import os
print(os.getcwd())

Example Output:

C:\Users\Balvinder\Documents

—————————————–

3. Changing Current Working Directory

Use os.chdir(path).

os.chdir("C:/Users/Public")
print(os.getcwd())

✔ Moves the program to another directory.
❌ Error if directory does not exist.


—————————————–

4. Creating Directories

Python offers two methods:


A. Create a Single Directory

os.mkdir("new_folder")

✔ Creates one folder
❌ Error if parent directory doesn’t exist


B. Create Nested Directories

os.makedirs("parent/child/grandchild")

✔ Creates entire folder path
✔ No error if intermediate directories do not exist


—————————————–

5. Removing Directories

Two functions:


A. Remove an Empty Directory

os.rmdir("myfolder")

❌ Works only if folder is empty.


B. Remove Directory Tree (Non-Empty Folder)

Use shutil module:

import shutil
shutil.rmtree("myfolder")

⚠ Completely deletes folder and its contents
⚠ Use carefully


—————————————–

6. List Files and Subdirectories

os.listdir(path)

print(os.listdir("."))

Example Output:

['file1.txt', 'folder1', 'program.py']

If no path is provided, current directory is used.


—————————————–

7. Checking Existence of a Directory

os.path.exists("myfolder")    # True / False

Check if path is a directory:

os.path.isdir("myfolder")

—————————————–

8. Getting Absolute Path

print(os.path.abspath("myfolder"))

—————————————–

9. Joining Paths (Platform-Independent)

path = os.path.join("C:/Users", "Documents", "Projects")
print(path)

✔ Safer than writing paths manually
✔ Works on Windows, macOS, Linux


—————————————–

10. Renaming a Directory

os.rename("old_folder", "new_folder")

—————————————–

11. Directory Tree Traversal

Use os.walk() to explore folders recursively.

for root, dirs, files in os.walk("C:/Projects"):
    print("Directory:", root)
    print("Subdirectories:", dirs)
    print("Files:", files)

—————————————–

12. Example Program Using Directory Operations

import os

# Create directory
os.mkdir("TestFolder")

# List directories
print("Current files:", os.listdir("."))

# Rename directory
os.rename("TestFolder", "MyFolder")

# Check existence
print(os.path.exists("MyFolder"))

# Remove directory
os.rmdir("MyFolder")

—————————————–

Exam-Ready Summary

Python handles directories using the os module. The mkdir() and makedirs() functions create directories, while rmdir() and shutil.rmtree() remove them. The current directory can be obtained using getcwd() and changed using chdir(). Directory contents can be listed with listdir(), and path utilities are available in the os.path module. These operations help manage and organize files efficiently.