首页 > 解决方案 > 在Finder中获取文件的文件路径

问题描述

我想在 Finder 中获取前端文件的文件路径,例如/Users/user/Downloads/file.png,我对macOSAppleScript 处理文件路径的方式感到非常困惑,POSIX 带有斜线,而本机带有冒号。我尝试了这两个:

tell application "Finder"
    set temp to selection
    repeat with i from 1 to length of temp
        set the_item to item i of temp
        
        set item_posix to the_item as POSIX file
        set the_result to POSIX path of item_posix -- returns only the file's name and extension
        
        return get the path of the_item -- returns an error
    end repeat
end tell

我曾经成功过,它是如此令人费解,as file以至于as alias我不记得它是如何工作的。

如何在 Finder 中获取前端文件的文件路径?

更新:为了语法,我对单个路径感兴趣,我可以使用循环处理多个路径。

标签: applescriptfilepathfinder

解决方案


在 Finder 中,该selection属性始终返回Finder 文件说明符列表或空列表。

使用您的语法的最简单方法是强制选择alias list并从别名获取 POSIX 路径

tell application "Finder"
    set temp to selection as alias list
    repeat with i from 1 to length of temp
        set the_item to item i of temp           
        set the_result to POSIX path of the_item
        
        return the_result
    end repeat
end tell

POSIX file只需要相反的情况,从 POSIX 路径获取 HFS 路径或别名。

如果您只想要第一项,则selection不需要循环,但必须检查空列表

tell application "Finder"
    set temp to selection as alias list
    if temp is not {} then            
       return POSIX path of item 1           
    end if
end tell

推荐阅读