Deleting files and directories in Python ⋆ ALexHost SRL

Test your skills on our all Hosting services and get 15% off!

Use code at checkout:

Skills
21.01.2025

Deleting files and directories in Python

In Python, working with files and directories is a common task, especially for applications that require file manipulation. This tutorial focuses on advanced methods for deleting files and directories using various Python modules, including os, shutil, and pathlib. Each of these modules provides different functionality for working with the file system, allowing you to efficiently manage files and directories. To download Python, visit the following link from the official source python.org.

Understanding the modules

1. Module os

The os module provides the ability to use operating system-dependent functionality, such as reading or writing to the file system. It includes file and directory deletion functions. Using the os module in a Linux VPS hosting environment provides effective control over file management and other system-level operations. This module allows developers to perform actions such as reading, writing, and deleting files and directories directly on the server

Key features:

  • os.remove(path): Removes the path to a file.
  • os.rmdir(path): Removes (destroys) the path to a directory. The directory must be empty.
  • os.unlink(path): Another name for the os.remove() function used to delete a file.

2. Module shutil

The shutil module offers a high-level interface for working with files. It is particularly useful for copying and deleting directories and files.

Key features:

  • shutil.rmtree(path): Recursively removes a directory and all its contents, including subdirectories and files.
  • shutil.move(src, dst): Moves a file or directory to another location. Can also be used to delete files by moving them to a nonexistent directory.

3. Pathlib module

The pathlib module provides an object-oriented approach to working with file system paths. This module appeared in Python 3.4 and is considered more intuitive and easier to read.

Key features:

  • Path.unlink(): Deletes the file.
  • Path.rmdir(): Deletes an empty directory.
  • Path.rmtree(): To delete a directory and its contents, shutil.rmtree() is typically used in conjunction with Path.

Advanced methods for deleting files and directories

Using the os module

Here’s how to use the os module to delete files and directories:

Option A: Running in Interactive Python

  1. Open an interactive Python session by typing:
    python3

    (Use python if that’s how Python is configured on your system, but python3 is usually the recommended command for Python 3.x).

  2. Copy and paste the code directly into the interactive session (script below)

bird B: Writing to a Python script file

  1. Create a new file using a text editor such as nano:
    nano remove_file.py
  2. Copy and paste the following code into the file (script below)
  3. You can now run your Python script from the terminal:
    python3 remove_file.py

Removing a single file

import os
file_path = 'example.txt'
try:
os.remove(file_path)
print(f'Successfully deleted {file_path}')
except FileNotFoundError:
print(f'The file {file_path} does not exist')
except PermissionError:
print(f'Permission denied: unable to delete {file_path}')
except Exception as e:
print(f'An error occurred: {e}')

Output:

Deleting an empty directory

Step 1: Create a directory

First, create an empty directory named example_dir. This can be done using the following command:

mkdir example _dir

Step 2: Create a Python script

Now you need to create a Python script that will contain the code to delete the empty directory. You can use a text editor such as nano to create the script.

  1. Open nano and create a new Python file:
    nano remove_directory.py
  2. Copy and paste the following code into the file (code below)
  3. Now run the Python script you just created:
    python3 remove_directory.py

import os
directory_path = 'example_dir'
try:
os.rmdir(directory_path)

f'Successfully deleted directory {directory_path}')
except FileNotFoundError:
print(f'The directory {directory_path} does not exist')
except OSError:
print(f'The directory {directory_path} is not empty')
except Exception as e:
print(f'An error occurred: {e}')

Output:

Using the shutil module

Step 1: Create a directory with the contents

First, create a directory named example_dir_with_content and add some files to it. This can be done using the following commands:

mkdir example_dir_with_content
touch example_dir_with_content/file1.txt
touch example_dir_with_content/file2.txt

Step 2: Create a Python script

Now you need to create a Python script containing the code to delete the directory and its contents. You can use a text editor such as nano to create the script.

  1. Open nano and create a new Python file:
    nano remove_directory_content.py
  2. Copy and paste the following code into the file (code below)
  3. Now run the Python script you just created:
    python3 remove_directory_content.py

Use shutil.rmtree() to remove directories with content:

import shutil
'example_dir_with_content'
try:
shutil.rmtree(directory_path)
print(f'Successfully deleted directory {directory_path} and its contents')
except FileNotFoundError:
print(f'The directory {directory_path} does not exist')
except PermissionError:
print(f'Permission denied: unable to delete {directory_path}')
except Exception as e:
print(f'An error occurred: {e}')

Output:

Using the pathlib module

thepathlib module provides a modern interface to file system paths:

Deleting a file

from pathlib import Path
file_path = Path('example.txt')
try:
file_path.unlink()
print(f'Successfully deleted {file_path}')
except FileNotFoundError:
print(f'The file {file_path} does not exist')
except PermissionError:
print(f'Permission denied: unable to delete {file_path}')
except Exception as e:
print(f'An error occurred: {e}')

Output:

Deleting an empty directory

from pathlib import Pathdirectory_path = Path('example_dir'
try:
directory_path.rmdir() # This will only work if the directory is empty
print(f'Successfully deleted directory {directory_path}')
except FileNotFoundError:
print(f'The directory {directory_path} does not exist')
except OSError:
print(f'The directory {directory_path} is not empty')
except Exception as e:
print(f'An error occurred: {e}')

Output:

Graceful error handling

When working with file operations, it is very important to handle exceptions gracefully to prevent the program from crashing. Common exceptions include:

  • FileNotFoundError: Occurs when an attempt is made to delete a non-existent file or directory.
  • PermissionError: Occurs when a user lacks the necessary permissions to delete a file or directory.
  • OSError: Occurs when various OS-related errors occur, including an attempt to delete a non-empty directory.

Conclusion

In this tutorial, we’ve covered how to use Python modules such as os, shutil, and pathlib to delete files and directories. Each module has unique advantages, and understanding how to use them effectively will expand your ability to manage file systems in your applications. By mastering these techniques, you will be able to automate file management tasks, work with files more intuitively, and write robust scripts that interact with the file system.

Test your skills on our all Hosting services and get 15% off!

Use code at checkout:

Skills