A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python-directory-management/ below:

Python Directory Management - GeeksforGeeks

Python Directory Management

Last Updated : 24 Jul, 2025

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 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.

Python
import os

# single directory
os.mkdir("my_directory")

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

Explanation:

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:

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:

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:

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.

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:

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
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()))

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.

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:

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:

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:

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.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4