使用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()
相关推荐
_Li.5 分钟前
机器学习-特征选择
人工智能·python·机器学习
魔镜前的帅比12 分钟前
Agent 错误恢复与回退策略
python·ai
叶子丶苏14 分钟前
第十九节_PySide6基本窗口控件深度补充_剪贴板与拖曳功能(Drag 与 Drop) 下篇
python·pyqt
猿饵块26 分钟前
python--锁
java·jvm·python
星辰落满衣40 分钟前
股票实时交易数据之Python、Java等多种主流语言实例代码演示通过股票数据接口
java·开发语言·python
F_D_Z1 小时前
哈希表解Two Sum问题
python·算法·leetcode·哈希表
智算菩萨1 小时前
【实战】使用讯飞星火API和Python构建一套文本摘要UI程序
开发语言·python·ui
Groundwork Explorer1 小时前
异步框架+POLL混合方案应对ESP32 MPY多任务+TCP多连接
python·单片机
梦帮科技2 小时前
Scikit-learn特征工程实战:从数据清洗到提升模型20%准确率
人工智能·python·机器学习·数据挖掘·开源·极限编程
xqqxqxxq2 小时前
Java 集合框架之线性表(List)实现技术笔记
java·笔记·python