Open In App

Python Directory Management

Last Updated : 24 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Python Directory Management refers to handling and interacting with directories (folders) on a filesystem using Python. It includes creating, deleting, navigating, renaming, and listing directory contents programmatically. Python provides built-in modules like os, os.path, pathlib and shutil module for these operations.

Why do we need Python Directory Management

  • Automates folder operations like creating, deleting, renaming and navigating directories.
  • Helps in organizing files and building structured workflows in scripts and applications.
  • Provides cross-platform support using built-in modules like os, os.path and pathlib.
  • Enables dynamic control over the working directory and supports nested folder handling.

os and os.path module

os module provides functions to interact with the operating system, such as managing directories, files, processes and environment variables. It is cross-platform and adapts to the underlying OS (e.g., Windows, Linux, macOS).

Creating new directory

Let's explore how to create a new directory using the os module in Python. This is useful when you want your program to generate folders dynamically.

  • os.mkdir(path): Creates a single directory at the specified path. Raises an error if the directory already exists.
  • os.makedirs(path): Creates a directory and any necessary parent directories. Useful for nested directory creation.
Python
import os

# single directory
os.mkdir("my_directory")

# nested directories
os.makedirs("parent_directory/child_directory")

Explanation:

  • os.mkdir("my_directory") creates a folder named my_directory in the current location.
  • os.makedirs() creates all intermediate-level directories needed to contain the leaf directory. for example, parent_directory and child_directory if they don't already exist.

Getting Current Working Directory (CWD)

os.getcwd(): Returns the absolute path of the current working directory where the script is running. Useful for determining where your script operates, especially when working with relative paths. It returns a string representing the directory path.

Python
import os

print("String format :", os.getcwd())
print("Byte string format :", os.getcwdb())

Output
String format : /home/guest/sandbox
Byte string format : b'/home/guest/sandbox'

Explanation:

  • os.getcwd() returns the current working directory as a string.
  • os.getcwdb() returns the same path but in byte string format (b'').

Renaming a directory

os.rename(src, dst): Renames a directory (or file) from src to dst. The source (src) must exist and the destination (dst) should not already exist.

Example:

Python
import os

# Simple rename
os.rename("my_directory", "renamed_directory")

# Rename and move to another path
os.renames('my_directory', 'renamed_directory')

Explanation:

  • os.rename() changes the name of a file or directory. If "my_directory" exists, it's renamed to "renamed_directory".
  • os.renames() also renames the directory, and if the path doesn’t exist, it creates intermediate directories as needed.

Changing Current Working Directory (CWD)

os.chdir(path): Changes the current working directory to the specified path. After changing, all relative paths are resolved concerning the new working directory. If the specified path does not exist, an OSError is raised.

Example:

Python
import os
print("Current directory :", os.getcwd())

# Changing directory
os.chdir('/home/nikhil/Desktop/')
print("Current directory :", os.getcwd())

Output:

Current directory : /home/nikhil/Desktop/gfg
Current directory : /home/nikhil/Desktop

Explanation:

  • os.getcwd() shows the current path.
  • os.chdir() changes the current working directory to /home/nikhil/Desktop/.

Listing Files in a Directory

os.listdir(path) returns a list of the names of files and directories in the specified directory. The "." refers to the current directory. Use ".." to refer to the parent directory. The method does not recursively list contents of subdirectories. For recursion, use os.walk().

For example: Listing the files in the CWD- GeeksforGeeks (root directory)

Python
import os
print("Files in CWD are :", os.listdir(os.getcwd()))

Output
Files in CWD are : ['output.txt', 'input.txt', 'driver', 'Solution.py']

Explanation: os.listdir() lists all files and folders in the current working directory (os.getcwd()).

Removing a directory

Let’s explore how to remove directories in Python using the os and shutil modules. This is useful when you want to clean up empty folders or delete entire directory trees dynamically.

  • os.rmdir(path): Removes an empty directory. Use os.rmdir() for empty directories; otherwise, an error is raised.
  • shutil.rmtree(path): Removes a directory and its contents recursively. Use shutil.rmtree() for non-empty directories. Be cautious as this is irreversible.

For example: Let us consider a directory K:/files. Now to remove it, one has to ensure whether it is empty and then proceed for deleting.

Python
import os
li=os.listdir('/')

if len(li)==0:
  print("Error!! Directory not empty!!")
else:
  os.rmdir('k:/files')

Explanation:

  • Checks if the directory / is empty using os.listdir('/').
  • If it's not empty, attempts to remove the directory 'k:/files' using os.rmdir() (only works if 'k:/files' is also empty).

Check Whether It Is a Directory

os.path.isdir(path): Returns True if the path is a directory, otherwise False. Often used before performing operations like os.rmdir() or os.listdir() to ensure the path is valid. Helps prevent errors during directory management.

Python
import os

cwd = '/'
print(os.path.isdir(cwd))  # True if cwd is a directory

other = 'K:/'
print(os.path.isdir(other))  # Checks another directory

Output
True
False

Get Size of the Directory

os.path.getsize(path) returns the size of a file in bytes. Use this with os.walk() to calculate directory size. os.walk() iterates through all subdirectories and files in a directory. Summing up file sizes gives the total directory size.

Python
import os
print(os.path.getsize(os.getcwd()))

Output
4096

Explanation: os.path.getsize() returns the size in bytes of the specified path. If it's a directory, it returns the metadata size (not total size of contents).

Getting Access and Modification Times

Let’s explore how to retrieve the last access and modification times of files or directories in Python. This is useful for tracking file usage, backups or system monitoring tasks.

  • os.path.getatime(path): Returns the last access time of a file or directory as a timestamp.
  • os.path.getmtime(path): Returns the last modification time as a timestamp.

Example : Getting access and modification time of GeeksforGeeks (root) directory

Python
import time
import os
# Get times
access_time = os.path.getatime("/")
modification_time = os.path.getmtime("/")

# Convert to readable format
print("Access Time:", time.ctime(access_time))
print("Modification Time:", time.ctime(modification_time))

Output
Access Time: Sat Jan  4 09:21:37 2025
Modification Time: Sat Jan  4 09:21:37 2025

Explanation: time.ctime() converts the timestamp into human-readable format.

shutil module

shutil module in Python is a high-level file and directory management library. It provides functions for copying, moving and removing files and directories.

shutil.copytree()

Recursively copies an entire directory tree (source directory and all its contents) to a destination. Creates a new directory at the destination path and copies all files and subdirectories. Raises FileExistsError if the destination exists and dirs_exist_ok is False.

Syntax:

shutil.copytree(src, dst, dirs_exist_ok=False)

Parameters:

  • src: Path to the source directory.
  • dst: Path to the destination directory.
  • dirs_exist_ok: If True, allows copying into an existing directory. If False (default), raises an error if the destination already exists.

Example:

Python
import shutil

shutil.copytree("source_dir", "destination_dir")
print("Directory copied successfully")

Explanation: Recursively copies the contents of source_dir (including files and subdirectories) into a new destination_dir.

shutil.rmtree()

Deletes an entire directory tree, including all its files and subdirectories. This operation is irreversible. Be careful when specifying the path.

Syntax:

shutil.rmtree(path, ignore_errors=False)

Parameters:

  • path: Path to the directory to be removed.
  • ignore_errors: If True, ignores errors during removal. If False (default), raises an error.

Example:

Python
import shutil

shutil.rmtree("destination_dir")
print("Directory removed successfully")

Explanation: Recursively deletes destination_dir and all its contents.

shutil.move(s,d)

Moves a file or directory to a new location. If the source and destination are on the same filesystem, this is equivalent to renaming. Otherwise, it copies the source to the destination and then deletes the original.

Syntax:

shutil.move(src, dst)

Parameters:

  • src: Path to the source file or directory.
  • dst: Path to the destination file or directory.

Example:

Python
import shutil

shutil.move("source_dir", "new_location")
print("Directory moved successfully")

Explanation: Moves the entire source_dir to new_location. If both are on the same filesystem, it's a rename operation otherwise, it copies and deletes the source.


Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy