欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > 使用Python恢复Windows、Linux、MacOS回收站中的文件和目录

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

2025/4/19 10:12:01 来源:https://blog.csdn.net/limengshi138392/article/details/141504737  浏览:    关键词:使用Python恢复Windows、Linux、MacOS回收站中的文件和目录

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

import os
import platformdef put_back_trash():# 获取操作系统类型os_type = platform.system()if os_type == "Windows":  # Windowsfrom winshell import recycle_binfor item in recycle_bin():winshell.undelete(item.original_filename())else:print("Unsupported operating system.")put_back_trash()

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

import os
import platform
import shutil
import urllib.parsedef 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 Nonedef 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}')returnif os.path.exists(original_path):print(f'Error: File {original_path} already exists')returntrash_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":  # Linuxrestore_linux_all_files()else:print("Unsupported operating system.")put_back_trash()

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

import os
import platform
import shutil
import urllib.parsedef put_back_trash():# 获取操作系统类型os_type = platform.system()if os_type == "Darwin":  # macOSdef generate_applescript():script = '''tell application "Finder"activateset file_count to count of (trash's items)-- log file_countrepeat file_count timesrecoverMyFile() of meend repeatend tellon recoverMyFile()tell application "System Events"set frontmost of process "Finder" to truetell application "Finder"open trashselect the first item of front windowend telltell process "Finder"key code 51 using command downdelay 2 -- Yes, it's stupid, but necessary :(end tellend tellend 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()

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词