2015-06-13 2 views
2

Я в замешательстве. Я проработал в течение часа и пробовал, вероятно, десять различных форм set posixDirectory to POSIX path of (parent of (path to aFile) as string), но я не могу понять, что это правильно.Получение каталога входного файла (Applescript)

Я получаю путь полный POSIX (включая имя файла), делая set posixFilePath to POSIX path of aFile

Теперь, как я получаю POSIX путь только директории ?? Я получаю различные ошибки в зависимости от того, что я ... не могу сделать псевдоним .. не может получить родительский псевдоним ...

Я думаю, что это должно работать, но это не ... set posixDirectory to POSIX path of ((parent of aFile))

ответ

7

Существует несколько способов сделать это, если у вас уже есть исходный путь.

С Posix формат пути

set thePath to "/Users/USERNAME/Documents/Test/selectedTextColour.css" 


set textNumber1 to characters 1 thru -((offset of "/" in (reverse of items of thePath as string)) + 1) of thePath as string 

или с помощью оболочки

set thePath to "/Users/USERNAME/Documents/Test/selectedTextColour.css" 


set parentPath to do shell script "dirname " & quoted form of thePath 

Результат: "/Users/USERNAME/Documents/Test"


Из формата файла Posix

set thePath to "Macintosh HD:Users:USERNAME:Documents:Test:selectedTextColour.css" 


set textNumber1 to characters 1 thru -((offset of ":" in (reverse of items of thePath as string)) + 1) of thePath as string 

Результат: "Macintosh HD:Users:USERNAME:Documents:Test"

+0

@Max если это решить ваш ответ, вы должны принять его или, если не из ответов сделать, объясните, пожалуйста, почему и мы можем попробовать и исправить ее. – markhunte

5

Используйте контейнер команду Finder:

set aFile to choose file 

tell application "Finder" to set posixDirectory to POSIX path of ((container of aFile) as text) 
1

Попробуйте подпрограмму 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 
2

Этого должно быть достаточно на самом деле, когда у вас уже есть Posix путь к файлу.

to parentFolOfPxPath for pxPath 
    -- Assumes no superfluous slashes 
    set {tids, text item delimiters, i} to {text item delimiters, "/", ((pxPath ends with "/") as integer) + 1} 
    set {parFol, text item delimiters} to {text 1 thru text item -(i + 1) of pxPath, tids} 
    return parFol 
end parentFolOfPxPath 
Смежные вопросы