尝试子程序parentFolderOf(localPath)
。 localPath
可以是alias
,alias as text
或posix path
。它返回一个参考,你可以用Finder
使用,就像这样:
set thisItem to parentFolderOf(path to fonts folder)
tell application "Finder" to reveal thisItem
这里的脚本:
log (path to fonts folder)
log parentFolderOf(path to fonts folder)
log parentFolderOf(POSIX path of (path to fonts folder as text)) as text
log parentFolderOf("/System")
log parentFolderOf("/System") as text
# lets generate an error:
# parentFolderOf("ThisGeneratesAnError")
on parentFolderOf(localPath)
if (class of localPath is text) and (localPath contains ":") then
try
set localPath to localPath as alias
on error
error "File missing!"
end try
end if
# if its not an alias and not text containing ":" we assume its a posix path
if not (class of localPath is alias) then
try
set localPath to (localPath as POSIX file) as alias
on error
error "File missing!"
end try
end if
-- get the container:
set localPathContainerPath to ""
tell application "Finder"
try
set localPathContainerPath to (get container of localPath)
end try
end tell
return localPathContainerPath
end parentFolderOf
加成 MCUSR的做法似乎是一个不错的策略因为没有必要使用Finder
(如果物品丢失,会引发错误)。这里的一个版本,其输入与alias
,(alias as text)
或posix path
工作:
log (parentFolder for (path to me))
log (parentFolder for "/Root/Sub1/Sub2/Sub3/testFile.txt")
log (parentFolder for "/Root/Sub1/Sub2/Sub3////")
log (parentFolder for "///Root/Sub1/Sub2/Sub3////")
log (posixPath for (path to me))
to parentFolder for aPath
set aPath to posixPath for aPath
set {tids, text item delimiters, i} to {text item delimiters, "/", ((aPath ends with "/") as integer) + 1}
set {pF, text item delimiters} to {text 1 thru text item -(i + 1) of aPath, tids}
return pF
end parentFolder
to posixPath for aPath
if class of aPath is not text then set aPath to aPath as text
if aPath contains ":" then set aPath to POSIX path of aPath
repeat while aPath starts with "//"
set aPath to (characters 2 thru -1 of aPath) as text
end repeat
repeat while aPath ends with "//"
set aPath to (characters 1 thru -2 of aPath) as text
end repeat
return aPath
end posixPath
@Max如果这解决了你的答案,你应该接受它,如果答案不这样做,请解释原因,我们可以尝试和纠正它。 – markhunte