Python Directory Management (original) (raw)

Directory Management involves performing operations such as creating, deleting, renaming, navigating and listing directories using code. It helps in handling folder structures programmatically using built-in modules like os, pathlib and shutil.

Why do we need 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.

Creating new directory

A new directory can be created using below function:

**Example: This code creates one simple directory and one nested directory.

Python `

import os os.mkdir("my_directory") # single directory os.makedirs("parent_directory/child_directory") # nested directories

`

**Explanation:

Getting Current Working Directory (CWD)

Current Working Directory (CWD) is the location from which the Python script is being executed. To know where the current python script is running, use below function:

**Example: This code prints the current working directory in two formats.

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

To rename a folder or move it to a different location, the following functions are used:

**Example: This code shows both simple renaming and renaming with path changes.

Python `

import os

Simple rename

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

Rename and create missing parent directories if needed

os.renames("old_dir", "new_parent/new_child/renamed_directory")

`

**Explanation:

Changing Current Working Directory (CWD)

You can change where your script is working from. This helps when you want to run file operations inside a specific folder. os.chdir(path) changes the working directory to the given path.

**Example: This code shows the directory before and after changing it.

Python `

import os print("Before changing directory:", os.getcwd()) os.chdir('/home/nikhil/Desktop/') print("After changing directory:", os.getcwd())

`

**Output

Before changing directory: /home/nikhil/Desktop/gfg
After changing directory: /home/nikhil/Desktop

**Explanation:

Listing Files in a Directory

You can get the names of all files and folders inside a directory.

**Example: This code lists everything in the current 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

Directories can be removed, but methods differ depending on whether they are empty or contain files.

**Example: This code checks if a directory is empty before deleting it.

Python `

import os dir_path = "k:/files" if not os.listdir(dir_path): os.rmdir(dir_path) print("Directory removed successfully") else: print("Error! Directory not empty.")

`

**Explanation:

Check Whether It Is a Directory

Before performing operations, it’s good practice to confirm if a given path is actually a directory.os.path.isdir(path) Returns True if the path is a directory, else False.

**Example: This code checks two paths to see if they are directories.

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

`

Working with Directories using pathlib

pathlib is a modern, object-oriented alternative to os and os.path.

**Example: This code creates a folder and lists files in the current directory.

Python `

from pathlib import Path Path("my_new_dir").mkdir(exist_ok=True) for file in Path(".").iterdir(): print(file)

`

**Explanation:

Get Size of the Directory

To calculate the size of a directory, you need to add up the sizes of all its files (recursively).

**Example: This code computes the total size of the current directory.

Python `

import os total_size = 0 for dirpath, dirnames, filenames in os.walk(os.getcwd()): for f in filenames: fp = os.path.join(dirpath, f) total_size += os.path.getsize(fp)

print("Total directory size:", total_size, "bytes")

`

**Output

Total directory size: 23541 bytes

**Explanation: os.walk() iterates through all files in the directory tree and os.path.getsize() adds up their sizes, giving the total size of contents.

Getting Access and Modification Times

To retrieve the last access and modification times of files or directories use below functions:

**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 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: This code copies all files and folders from source_dir into destination_dir.

Python `

import shutil shutil.copytree("source_dir", "destination_dir", dirs_exist_ok=True) 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: This code permanently deletes the destination_dir folder and everything inside it.

Python `

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

`

**Explanation: Recursively deletes **destination_dir and all its contents.

**Tip: If you want safer deletion (sending files to recycle bin instead of permanent removal), use send2trash module instead of shutil.rmtree().

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: This code moves the entire source_dir folder into new_location.

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.