使用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()
相关推荐
迁旭11 分钟前
prompt_toolkit 3.0.52 API 参考手册
python
WL_Aurora13 分钟前
Python 算法基础篇之堆和优先队列
python·算法
早日退休!!!14 分钟前
PyTorch适配NPU
人工智能·pytorch·python
刀法如飞22 分钟前
一款开箱即用的Flask 3.0 MVC工程脚手架,面向AI开发
后端·python·flask
xingpanvip27 分钟前
星盘接口开发文档:组合三限盘接口指南
android·开发语言·前端·python·php·lua
vortex51 小时前
Villain:新一代轻量级 C2 框架完整使用指南
python·网络安全·kali·c2
测试员周周1 小时前
【AI测试系统】第5篇:AI 编码工具抛硬币?我们用 LangGraph 做了个“确定性+AI”的测试系统(附自愈架构)
人工智能·python·功能测试·测试工具·架构·langchain·单元测试
Levin__NLP_CV_AIGC1 小时前
py文件中文件复制方法
开发语言·python
庚昀◟1 小时前
腾讯云 CVM + Docker + Jenkins + GitLab CI/CD 全流程指南(python、flask实现简单计算器)
python·ci/cd·docker·flask·jenkins
H_unique1 小时前
LangChain:创建工具Ⅰ
python·langchain