Skip to main content
 首页 » 编程设计

python之OS X : Determine Trash location for a given path

2025年05月04日7youxin

简单地将文件移动到 ~/.Trash/ 是行不通的,就像外部驱动器上的文件 os 一样,它会将文件移动到主系统驱动器..

此外,还有其他情况,例如外部驱动器上的文件被移动到 /Volumes/.Trash/501/(或当前用户的 ID 是什么)

给定一个文件或文件夹路径,确定垃圾文件夹的正确方法是什么?我认为语言无关紧要,但我打算使用 Python

请您参考如下方法:

基于 http://www.cocoadev.com/index.pl?MoveToTrash 中的代码我想出了以下内容:

def get_trash_path(input_file): 
    path, file = os.path.split(input_file) 
    if path.startswith("/Volumes/"): 
        # /Volumes/driveName/.Trashes/<uid> 
        s = path.split(os.path.sep) 
        # s[2] is drive name ([0] is empty, [1] is Volumes) 
        trash_path = os.path.join("/Volumes", s[2], ".Trashes", str(os.getuid())) 
        if not os.path.isdir(trash_path): 
            raise IOError("Volume appears to be a network drive (%s could not be found)" % (trash_path)) 
    else: 
        trash_path = os.path.join(os.getenv("HOME"), ".Trash") 
    return trash_path 

相当基础,有一些事情必须单独完成,特别是检查文件名是否已经存在于回收站中(以避免覆盖)以及实际移动到回收站,但它似乎涵盖了大部分事情(内部,外部)和网络驱动器)

更新:我想在 Python 脚本中删除一个文件,所以我在 Python 中重新实现了 Dave Dribin 的解决方案:

from AppKit import NSURL 
from ScriptingBridge import SBApplication 
 
def trashPath(path): 
    """Trashes a path using the Finder, via OS X's Scripting Bridge. 
    """ 
    targetfile = NSURL.fileURLWithPath_(path) 
    finder = SBApplication.applicationWithBundleIdentifier_("com.apple.Finder") 
    items = finder.items().objectAtLocation_(targetfile) 
    items.delete() 

用法很简单:

trashPath("/tmp/examplefile")