Python Directory Management
Python Directory Management refers to handling and interacting with directories (folders) on a filesystem using Python. It includes creating, deleting, navigating and listing directory contents programmatically. Python provides built-in modules like os and os.path and the newer pathlib module, for this purpose.
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
- 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.
import os
# Create a single directory
os.mkdir("my_directory")
# Create nested directories
os.makedirs("parent_directory/child_directory")
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.
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'
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.
For example, consider there is a file named 'file1.txt' in current working directory. Now to just rename it :
os.rename("my_directory", "renamed_directory")
If renaming and moving the file to some other directory is required, then the code snippet should be:
import os
os.renames('my_directory', 'renamed_directory')
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.
For example, If we need to change the CWD to my_folder in D:/, then the following code snippet is used.
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
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)
import os
print("Files in CWD are :",os.listdir(os.getcwd()))
Output
Files in CWD are : ['output.txt', 'input.txt', 'driver', 'Solution.py']
Removing a directory
- 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.
import os
li=os.listdir('/')
if len(li)==0:
print("Error!! Directory not empty!!")
else:
os.rmdir('k:/files')
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.
import os
# current working directory of
# GeeksforGeeks
cwd='/'
print(os.path.isdir(cwd))
# Some other directory
other='K:/'
print(os.path.isdir(other))
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.
import os
print(os.path.getsize(os.getcwd()))
Output
4096
Getting Access and Modification Times
- 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
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
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:
import shutil
# Copy the entire directory tree
shutil.copytree("source_dir", "destination_dir")
print("Directory copied successfully")
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:
import shutil
# Remove a directory tree
shutil.rmtree("destination_dir")
print("Directory removed successfully")
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:
import shutil
# Move a directory to a new location
shutil.move("source_dir", "new_location")
print("Directory moved successfully")