且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AppleScript:如何获取文件夹中没有隐藏文件的文件?

更新时间:2021-09-04 22:30:11

使用System Events上下文而不是Finder:

  • 使用AppleShowAllFiles首选项 [1]

通常要快得多.

System Events上下文中使用file/folder对象的visible属性,您可以可预测地确定所有所有项,包括隐藏的项(默认情况下),或者只有 visible 个(带有whose visible is true):

Using the visible property of file / folder objects in the System Events context allows you to predictably determine either all items, including hidden ones (by default), or only the visible ones (with whose visible is true):

# Sample input path.
set the_path to POSIX path of (path to home folder)

tell application "System Events"

    set allVisibleFiles to files of folder the_path whose visible is true

end tell

只需省略whose visible is true即可包含隐藏文件.

Simply omit whose visible is true to include hidden files too.

用于引用预先存在的文件夹或根据需要创建它的代码与Finder上下文中的代码基本上相同:

The code for either referencing a preexisting folder or creating it on demand is essentially the same as in the Finder context:

# Sample input path.
set the_path to POSIX path of (path to home folder)

# Sample subfolder name
set the_subfolder_name to "subfolder"

tell application "System Events"

    if folder (the_path & the_subfolder_name) exists then
        set subfolder to folder (the_path & the_subfolder_name)
    else
        set subfolder to make new folder at folder the_path ¬
          with properties {name: the_subfolder_name}
    end if

end tell


[1] 为了可预测地排除隐藏的项目,基于Finder的解决方案不仅麻烦,而且具有巨大的副作用:


[1] In order to predictably exclude hidden items, a Finder-based solution is not only cumbersome but has massive side effects:

  • 您需要确定AppleShowAllFiles首选项(defaults read com.apple.Finder AppleShowAllFiles)的当前状态,
  • 然后将其关闭.
    • 然后 kill Finder使更改生效(它会自动重新启动)-这将在视觉上造成破坏
    • You need to determine the current state of the the AppleShowAllFiles preference (defaults read com.apple.Finder AppleShowAllFiles),
    • then turn it off.
      • then kill Finder to make the change take effect (it restarts automatically) - this will be visually disruptive
      • 然后再次杀死Finder ,以便恢复的值再次生效.
      • then kill Finder again so that the restored value takes effect again.