How to Securely Delete Files and Folders in Python
Yamil Garcia
Tech enthusiast, embedded systems engineer, and passionate educator! I specialize in Embedded C, Python, and C++, focusing on microcontrollers, firmware development, and hardware-software integration.
In the era of digital information, data security has become paramount. Whether you're a developer handling sensitive user data or just someone concerned about privacy, knowing how to securely delete files and folders is crucial. Python, with its vast standard library and simple syntax, offers a straightforward way to accomplish this. In this article, we'll delve into how to write a Python script that can securely delete files and folders, ensuring that the data cannot be easily recovered.
Understanding the Basics
Before we dive into the code, it's important to understand what "secure deletion" means. When you delete a file using standard methods, the file is not immediately removed from the disk; instead, the space it occupies is marked as available for reuse. Until that space is overwritten with new data, the original data remains and can potentially be recovered using specialized tools.
To securely delete a file, we need to ensure that the data is overwritten with random or fixed patterns, making it irrecoverable. This process involves writing over the file multiple times before finally deleting it.
Setting Up the Environment
To get started, ensure you have Python installed on your system. This guide applies to Python 3.x versions. You'll not need any external libraries for the basic deletion script, as we'll be using modules like os, shutil, and random from Python's standard library.
Writing the Secure Deleter Class
Let's begin by defining a Python class named SecureDeleter that will handle the secure deletion of files and folders.
The __init__ method initializes the object with the path of the file or folder to be deleted.
Next, we define methods for overwriting and deleting files:
The overwrite_file method overwrites a file with zeros, ones, a random byte pattern, and then random data for a specified number of passes to make the data harder to recover.
To delete the file and folder securely, we implement the following methods:
The delete_file method calls overwrite_file before using os.remove to delete the file. The delete_folder method walks through the folder structure, securely deleting each file and then removing the empty directories.
For an optional but recommended step, we add a method to wipe free space on the drive, which helps in overwriting the spots where the deleted files were stored previously.
Finally, we define the execute method to determine whether the path is a file or a folder and delete it securely.
Using the SecureDeleter Class
To use the SecureDeleter class, instantiate it with the path of the file or folder you wish to delete securely, and call the execute method:
Optionally, you can call the wipe_free_space method after deletion to overwrite the free disk space:
Conclusion
Writing a Python script for securely deleting files and folders is a powerful way to enhance data security. By understanding and implementing the methods described in this guide, you can protect sensitive information from unauthorized recovery. Always test your scripts in a safe environment before using them with important data, and remember that the effectiveness of software-based file deletion can vary based on the storage technology used.
Code to Copy
import os
import shutil
import random
class SecureDeleter:
def __init__(self, path):
self.path = path
def overwrite_file(self, file_path, passes=7):
"""Overwrites the file with multiple patterns and random data."""
patterns = [b'\x00', b'\xFF', random.randbytes(1)]
print(patterns)
length = os.path.getsize(file_path)
for _ in range(passes):
with open(file_path, "r+b") as file:
for pattern in patterns:
file.seek(0)
for _ in range(length):
file.write(pattern)
# Final pass with random data for each byte
file.seek(0)
file.write(random.randbytes(length))
def delete_file(self, file_path):
"""Securely deletes a file."""
if os.path.isfile(file_path):
self.overwrite_file(file_path)
os.remove(file_path)
def delete_folder(self, folder_path):
"""Securely deletes a folder and its contents."""
if os.path.isdir(folder_path):
for root, dirs, files in os.walk(folder_path, topdown=False):
for name in files:
file_path = os.path.join(root, name)
self.delete_file(file_path)
for name in dirs:
os.rmdir(os.path.join(root, name))
shutil.rmtree(folder_path)\
def wipe_free_space(self, drive, size=1024*1024*10): # 10MB default file size
"""Writes temporary files with random data to overwrite free disk space."""
temp_files = []
try:
while True:
temp_file = os.path.join(drive, f"temp_{random.randint(0, 999999)}.dat")
with open(temp_file, "wb") as file:
file.write(random.randbytes(size))
temp_files.append(temp_file)
except OSError: # Typically disk full
for temp_file in temp_files:
os.remove(temp_file)
def execute(self):
"""Determines whether the path is a file or folder and deletes it securely."""
if os.path.isfile(self.path):
self.delete_file(self.path)
elif os.path.isdir(self.path):
self.delete_folder(self.path)
else:
print("Path does not exist.")
# Usage example:
deleter = SecureDeleter("/path/to/your/file_or_folder")
deleter.execute()