dbr*_*dbr 1 python filesystems macos
只需将文件移动到~/.Trash/
不起作用,就像外部驱动器上的文件操作系统一样,它会将文件移动到主系统驱动器中.
此外,还有其他条件,如外部驱动器上的文件被移动到/Volumes/.Trash/501/
(或当前用户的ID是什么)
给定文件或文件夹路径,确定垃圾文件夹的正确方法是什么?我想这种语言非常无关紧要,但我打算使用Python
或者,如果您使用的是OS X 10.5,则可以使用Scripting Bridge通过Finder删除文件.我在Ruby代码做到了这一点在这里通过RubyCocoa.它的要点是:
url = NSURL.fileURLWithPath(path)
finder = SBApplication.applicationWithBundleIdentifier("com.apple.Finder")
item = finder.items.objectAtLocation(url)
item.delete
Run Code Online (Sandbox Code Playgroud)
你可以轻松地用PyObjC做类似的事情.
根据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
Run Code Online (Sandbox Code Playgroud)
相当基本,有几件事需要单独完成,尤其是检查文件名是否已存在于垃圾箱中(以避免覆盖)以及实际移至垃圾箱,但它似乎涵盖了大多数内容(内部,外部和网络驱动器) )
更新:我想在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()
Run Code Online (Sandbox Code Playgroud)
用法很简单:
trashPath("/tmp/examplefile")
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3387 次 |
最近记录: |