嘗試子程序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