Contents

Exploring Directory Operations in Python

Learn to Create, Access, List, Rename, and Delete Directories with Examples

Website Visitors:

Working with Directories in Python

Directories, also known as folders, are an essential part of organizing and managing files on a computer. In Python, there are built-in modules and functions that allow you to work with directories efficiently. This article will guide you through various operations involving directories, including creating, accessing, listing, renaming, and deleting directories, along with multiple code examples for each.

Creating Directories

To create a directory in Python, you can use the os module, which provides a cross-platform way of interacting with the operating system. The os module contains the mkdir() function, which allows you to create a new directory.

Here’s an example that demonstrates how to create a directory named “new_directory”:

1
2
3
4
import os

directory_name = "new_directory"
os.mkdir(directory_name)

In the above code, we import the os module and specify the name of the directory we want to create (“new_directory”). Then, we call the mkdir() function, which creates a new directory with the specified name in the current working directory.

You can also create directories with nested structures using the os.makedirs() function. This function creates all the intermediate directories if they don’t exist.

1
2
3
4
import os

directory_path = "path/to/nested_directory"
os.makedirs(directory_path)

In this example, the makedirs() function creates a directory with the path “path/to/nested_directory,” creating any intermediate directories if they don’t already exist.

Accessing Directories

To work with directories, it’s important to know the current working directory and how to change it. The current working directory is the directory from which your Python script is executed.

The os module provides the getcwd() function, which allows you to retrieve the current working directory:

1
2
3
4
import os

current_directory = os.getcwd()
print("Current Directory:", current_directory)

The getcwd() function returns a string representing the current working directory. In the above code, we use print() to display the current working directory.

If you need to change the current working directory, you can use the chdir() function from the os module:

1
2
3
4
import os

new_directory = "/path/to/new_directory"
os.chdir(new_directory)

In the code snippet above, we specify the path to the new directory we want to switch to ("/path/to/new_directory"). The chdir() function changes the current working directory to the specified path.

Listing Directories

To list the contents of a directory, you can use the os.listdir() function. This function returns a list of all files and directories present in the specified directory.

Here’s an example:

1
2
3
4
5
6
7
8
import os

directory_path = "/path/to/directory"
contents = os.listdir(directory_path)

print("Contents of", directory_path + ":")
for item in contents:
    print(item)

In the above code, we provide the path to the directory whose contents we want to list ("/path/to/directory"). The listdir() function returns a list of items (files and directories) within that directory. We then iterate over the list using a for loop and print each item.

You can also use the os.scandir() function, which provides a more efficient way of listing directory contents, especially for large directories:

1
2
3
4
5
6
7
8
import os

directory_path = "/path/to/directory"

with os.scandir(directory_path) as entries:
    print("Contents of", directory_path + ":")
    for entry in entries:
        print(entry.name)

In this example, we use the scandir() function to efficiently iterate

over the directory contents. The with statement ensures that the directory is properly closed after use.

Renaming Directories

To rename a directory, you can use the os.rename() function from the os module. This function takes two arguments: the current name of the directory and the desired new name.

Here’s an example:

1
2
3
4
5
6
import os

old_name = "/path/to/old_directory"
new_name = "/path/to/new_directory"

os.rename(old_name, new_name)

In the code snippet above, we specify the current name of the directory we want to rename ("/path/to/old_directory") and the new name we want to assign ("/path/to/new_directory"). The rename() function renames the directory accordingly.

Deleting Directories

To delete a directory, you can use the os.rmdir() function from the os module. This function removes an empty directory specified by its path.

Here’s an example:

1
2
3
4
5
import os

directory_to_delete = "/path/to/directory"

os.rmdir(directory_to_delete)

In the above code, we provide the path to the directory we want to delete ("/path/to/directory"). The rmdir() function deletes the directory if it is empty. If the directory contains any files or subdirectories, an error will be raised.

To delete a directory and its contents recursively, you can use the shutil.rmtree() function from the shutil module. Be cautious when using this function, as it permanently deletes files and subdirectories.

1
2
3
4
5
import shutil

directory_to_delete = "/path/to/directory"

shutil.rmtree(directory_to_delete)

In this example, the rmtree() function recursively deletes the directory and all its contents.

Check if directory or file

The os.path.isdir() function is a method provided by the os.path module in Python. It is used to check whether a given path refers to an existing directory or not. It returns True if the path is a directory, and False otherwise.

Here’s an example of how to use os.path.isdir():

1
2
3
4
5
6
7
8
import os

path = "/path/to/directory"

if os.path.isdir(path):
    print("The path", path, "is a directory.")
else:
    print("The path", path, "is not a directory.")

In the above code, we provide the path variable with the directory path we want to check. The os.path.isdir() function is used within an if statement to determine if the path is a directory. If it is, the first print statement is executed, confirming that the path is a directory. Otherwise, the second print statement is executed, indicating that the path is not a directory.

List contents of folder are files or folders

Here is a sample script using which you can find files or folders exist in a folder.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import os
list = os.getcwd()

#print current directory
print("Current Directory: "+ list)

# list all files and directories in current directory
print(os.listdir(list))
# You can also call listdir and getcwd directly as shown below:
print(os.listdir(os.getcwd()))

fileslist = os.listdir(os.getcwd())
for item in fileslist:
    if os.path.isdir(item):
        print(item + " is a directory")
    else:
        print(item + " is a file")

Conclusion

Working with directories in Python is made easy with the help of the os module. You can create, access, list, rename, and delete directories using the functions provided by this module. By understanding and applying these concepts, you’ll be able to efficiently organize and manage directories and files within your Python scripts or applications.

Remember to handle exceptions appropriately when working with directories to handle cases such as permissions errors or non-existent directories.

Your inbox needs more DevOps articles.

Subscribe to get our latest content by email.