Cross-Platform Recycle Bin Management with Python
Sending Files to Recycle Bin
Python doesn't provide native APIs for moving files to the recycle bin, but the third-party send2trash module offers cross-platform functionality for Windows, macOS, and Linux systems.
Install the module using:
pip install send2trash
The module provides a send2trash function that accepts file or dircetory paths:
from send2trash import send2trash
import os
# Create test directory structure
os.makedirs('data_folder', exist_ok=True)
# Create sample files
with open('sample.txt', 'w') as f:
f.write('Test content')
with open('data_folder/nested_file.txt', 'w') as f:
f.write('Nested content')
# Move files to recycle bin
send2trash('sample.txt')
send2trash('data_folder')
Emptying Recycle Bin
Different opreating systems require different approaches for emptying the recycle bin.
Windows
Use the winshell module to empty Windows recycle bin:
pip install winshell
from winshell import recycle_bin
recycle_bin().empty(confirm=False, show_progress=False, sound=False)
macOS
Empty trash by removing all items from the ~/.Trash directory:
import glob
import shutil
import os
trash_path = os.path.expanduser("~/.Trash")
for item in glob.glob(f"{trash_path}/*"):
if os.path.isdir(item):
shutil.rmtree(item)
else:
os.remove(item)
Linux
Empty Linux trash by clearing the appropriate directory:
trash_path = os.path.expanduser("~/.local/share/Trash/files")
for item in glob.glob(f"{trash_path}/*"):
if os.path.isdir(item):
shutil.rmtree(item)
else:
os.remove(item)
Cross-Platform Implementation
import os
import shutil
import platform
import glob
def clear_trash():
system = platform.system()
if system == "Windows":
try:
from winshell import recycle_bin
recycle_bin().empty(confirm=False, show_progress=False, sound=False)
except ImportError as e:
print(f"winshell not available: {e}")
elif system == "Darwin":
trash_dir = os.path.expanduser("~/.Trash")
for item in glob.glob(f"{trash_dir}/*"):
try:
if os.path.isdir(item):
shutil.rmtree(item)
else:
os.remove(item)
except OSError as e:
print(f"Error removing {item}: {e}")
elif system == "Linux":
trash_dir = os.path.expanduser("~/.local/share/Trash/files")
for item in glob.glob(f"{trash_dir}/*"):
try:
if os.path.isdir(item):
shutil.rmtree(item)
else:
os.remove(item)
except OSError as e:
print(f"Error removing {item}: {e}")
if __name__ == "__main__":
clear_trash()
Restoring Files from Recycle Bin
Windows Restoration
Restore files using winshell module:
from winshell import recycle_bin
import shutil
import os
for item in recycle_bin():
shutil.copy2(item.filename, item.original_filename)
os.remove(item.filename)
macOS Restoration
Use AppleScript to restore files from trash:
applescript_code = '''
tell application "Finder"
activate
set item_count to count of (trash's items)
repeat item_count times
restore_item()
end repeat
end tell
on restore_item()
tell application "System Events"
set frontmost of process "Finder" to true
tell application "Finder"
open trash
select first item of front window
end tell
tell process "Finder"
key code 51 using command down
delay 2
end tell
end tell
end restore_item
'''
with open('restore_script.scpt', 'w') as f:
f.write(applescript_code)
import subprocess
subprocess.run(['osascript', 'restore_script.scpt'])
Linux Restoration
Restore files using metadata from trash info files:
import os
import glob
import configparser
from urllib.parse import unquote
def restore_linux_trash():
info_dir = os.path.expanduser("~/.local/share/Trash/info")
files_dir = os.path.expanduser("~/.local/share/Trash/files")
for info_file in glob.glob(f"{info_dir}/*.trashinfo"):
parser = configparser.ConfigParser()
parser.read(info_file)
original_path = unquote(parser['Trash Info']['Path'])
filename = os.path.basename(info_file).replace('.trashinfo', '')
trash_path = os.path.join(files_dir, filename)
if os.path.exists(trash_path):
shutil.move(trash_path, original_path)
os.remove(info_file)