Python Directory Management
Last Updated : 04 Jan, 2025
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.
Python 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.
Python import os print("String format :", os.getcwd()) print("Byte string format :", os.getcwdb())
OutputString 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 :
Python os.rename("my_directory", "renamed_directory")
If renaming and moving the file to some other directory is required, then the code snippet should be:
Python 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.
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
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()))
OutputFiles 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.
Python 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.
Python import os # current working directory of # GeeksforGeeks cwd='/' print(os.path.isdir(cwd)) # Some other directory other='K:/' print(os.path.isdir(other))
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()))
Getting Access and Modification Times
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))
OutputAccess 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.
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 # Copy the entire directory tree shutil.copytree("source_dir", "destination_dir") print("Directory copied successfully")
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 # Remove a directory tree shutil.rmtree("destination_dir") print("Directory removed successfully")
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 # Move a directory to a new location shutil.move("source_dir", "new_location") print("Directory moved successfully")
Similar Reads
Employee Management System using Python The task is to create a Database-driven Employee Management System in Python that will store the information in the MySQL Database. The script will contain the following operations : Add EmployeeRemove EmployeePromote EmployeeDisplay EmployeesThe idea is that we perform different changes in our Empl
8 min read
Health Management System using Python Sometimes we are so busy that we are not even able to care for our body and by caring we mean fitness, food, exercises and much more, and then we think that we need to make our diet plan or exercise plan to maintain our body. So let's make a Python script to maintain this record for us. In this prog
7 min read
Context Manager in Python In any programming language, the usage of resources like file operations or database connections is very common. But these resources are limited in supply. Therefore, the main problem lies in making sure to release these resources after usage. If they are not released then it will lead to resource l
3 min read
Python â The new generation Language INTRODUCTION: Python is a widely-used, high-level programming language known for its simplicity, readability, and versatility. It is often used in scientific computing, data analysis, artificial intelligence, and web development, among other fields. Python's popularity has been growing rapidly in re
6 min read
Disadvantages of Python Python is a widely used general-purpose, high-level programming language. It is widely used by developers in various domains, from web development to Machine Learning. However, Python has its own set of advantages and disadvantages. Let's see some limitations of Python programming language. Cons of
3 min read
Introduction to Python Pydantic Library In modern Python development, data validation and parsing are essential components of building robust and reliable applications. Whether we're developing APIs, working with configuration files, or handling data from various sources, ensuring that our data is correctly validated and parsed is crucial
6 min read