1

简单地将文件移动到~/.Trash/将不起作用,就好像外部驱动器上的文件操作系统一样,它将文件移动到主系统驱动器..

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

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

4

6 回答 6

5

或者,如果您使用的是 OS X 10.5,则可以使用 Scripting Bridge 通过 Finder 删除文件。我已经通过 RubyCocoa 在 Ruby 代码中完成了这项工作。它的要点是:

url = NSURL.fileURLWithPath(path)
finder = SBApplication.applicationWithBundleIdentifier("com.apple.Finder")
item = finder.items.objectAtLocation(url)
item.delete

你可以很容易地用 PyObjC 做类似的事情。

于 2008-10-30T20:07:26.547 回答
5

基于来自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")
于 2008-10-31T09:03:45.250 回答
3

更好的方法是NSWorkspaceRecycleOperation,这是您可以与-[NSWorkspace performFileOperation:source:destination:files:tag:]一起使用的操作之一。常量的名字是 Cocoa 的 NeXT 遗产的另一个产物。它的功能是将项目移动到垃圾箱。

由于它是 Cocoa 的一部分,因此它应该对 Python 和 Ruby 都可用。

于 2009-03-07T03:03:07.900 回答
3

在 Python 中,不使用脚本桥,您可以这样做:

from AppKit import NSWorkspace, NSWorkspaceRecycleOperation

source = "path holding files"
files = ["file1", "file2"]

ws = NSWorkspace.sharedWorkspace()
ws.performFileOperation_source_destination_files_tag_(NSWorkspaceRecycleOperation, source, "", files, None)
于 2011-02-16T04:56:14.090 回答
2

文件管理器 API 有一对称为 FSMoveObjectToTrashAsync 和 FSPathMoveObjectToTrashSync 的函数。

不确定这是否暴露于 Python。

于 2008-10-30T10:57:06.907 回答
1

另一个红宝石:

Appscript.app('Finder').items[MacTypes::Alias.path(path)].delete

你需要rb-appscript gem,你可以在这里阅读

于 2010-09-06T22:14:55.313 回答