使用Python恢复Windows、Linux、MacOS回收站中的文件和目录

一、使用Python恢复Windows回收站中的文件和目录

python 复制代码
import os
import platform

def put_back_trash():

    # 获取操作系统类型
    os_type = platform.system()

    if os_type == "Windows":  # Windows

        from winshell import recycle_bin

        for item in recycle_bin():
            winshell.undelete(item.original_filename())
        
    else:
        print("Unsupported operating system.")

put_back_trash()

二、使用Python恢复Linux回收站中的文件和目录

python 复制代码
import os
import platform
import shutil
import urllib.parse


def get_linux_original_path(filename):
    """
    获取回收站中文件的原始路径
    """

    trash_info_file = filename + '.trashinfo'

    trash_info_path = os.path.join(os.path.expanduser('~'), '.local/share/Trash/info', trash_info_file)

    with open(trash_info_path) as f:

        for line in f:

            if line.startswith('Path='):
                return urllib.parse.unquote(line[5:].strip())
    return None

def restore_linux_file(filename):
    """
    将文件从回收站移动到原始位置
    """

    original_path = get_linux_original_path(filename)

    if original_path is None:

        print(f'Error: Could not find original path for {filename}')
        return

    if os.path.exists(original_path):

        print(f'Error: File {original_path} already exists')
        return

    trash_file_path = os.path.join(os.path.expanduser('~'), '.local/share/Trash/files', filename)

    shutil.move(trash_file_path, original_path)

    print(f'Successfully restored {filename} to {original_path}')

def restore_linux_all_files():

    recycle_bin_path = os.path.expanduser("~/.local/share/Trash/files")

    for filename in os.listdir(recycle_bin_path):
        restore_linux_file(filename)

def put_back_trash():
    # 获取操作系统类型
    os_type = platform.system()

    if os_type == "Linux":  # Linux

        restore_linux_all_files()

    else:
        print("Unsupported operating system.")

put_back_trash()

三、使用Python恢复MacOS回收站中的文件和目录

python 复制代码
import os
import platform
import shutil
import urllib.parse


def put_back_trash():
    # 获取操作系统类型
    os_type = platform.system()

    if os_type == "Darwin":  # macOS

        def generate_applescript():

            script = '''tell application "Finder"
        	activate
        	set file_count to count of (trash's items)
        	-- log file_count
        	repeat file_count times
        		recoverMyFile() of me
        	end repeat
        end tell

        on recoverMyFile()
        	tell application "System Events"
        		set frontmost of process "Finder" to true
        		tell application "Finder"
        			open trash
        			select the first item of front window
        		end tell
        		tell process "Finder"
        			key code 51 using command down
        			delay 2 -- Yes, it's stupid, but necessary :(
        		end tell
        	end tell
        end recoverMyFile'''

            with open('apple.script', 'w') as f:
                f.write(script)

        def recover_macOS_all_files():

            generate_applescript()

            os.system("osascript apple.script")

        recover_macOS_all_files()

    else:
        print("Unsupported operating system.")

put_back_trash()
相关推荐
circuitsosk7 分钟前
大模型本体安全防护实践:提示词注入防御、输出合规过滤与敏感信息脱敏
python·安全·数据脱敏·纵深防御·提示词注入·llmsecurity
工业一体机老司机34 分钟前
Python实现工业一体机Modbus-TCP通信-从协议解析到多设备轮询实战
开发语言·python·tcp/ip
2401_8858850440 分钟前
国际语音php接口代码示例:PHP使用cURL快速调用语音发送API
android·开发语言·前端·人工智能·python·php·语音识别
EW Frontier1 小时前
基于 Python + NumPy 的雷达信号处理仿真平台设计与实现——从 LFM 波形到 CFAR 检测的完整信号链
python·雷达信号处理·cfar\]·mti·mtd
axinawang1 小时前
Tesseract入门--把图片里印刷文字提取成文本
python
青 春 记 忆1 小时前
LeetCode 283. 移动零|Python 解法详解
python·算法·leetcode
人工干智能1 小时前
科普:Python中的生成器——带`yield`的函数
开发语言·python
whcyhhh1 小时前
头歌实践教学平台:数据科学与大数据技术导论(十四)
大数据·开发语言·python
清水白石0081 小时前
Python dataclass 高级避坑指南:从 default_factory、frozen、slots 到哈希灾难
windows·python·哈希算法
在学了加油1 小时前
阿尔茨海默病诊断(优化特征选择版)
人工智能·python·dnn