You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过AppleScript创建文本文件并在创建后立即打开该文件

解决方案

你只需要捕获make命令返回的新建文件对象,再调用打开命令即可,以下是修改后的完整可运行代码:

tell application "Finder"
  try
    set fileName to "untitled"
    if length of fileName = 0 then
        return 0
    end if
    set fileExt to ".txt"
    set thisFolder to the target of the front window as alias
    set newFile to fileName & fileExt
    
    -- 捕获创建的文件对象
    set createdFile to make new file at thisFolder with properties {name:newFile, file type:"TEXT", creator type:"ttxt"}
    -- 直接用默认关联程序打开新建文件
    open createdFile
    
    on error errMsg
    display dialog (errMsg)
  end try
end tell

可选打开配置

  • 上述代码默认调用系统设置的txt文件默认打开程序启动文件
  • 如果需要固定用系统自带的「文本编辑」打开,替换open createdFile行为tell application "TextEdit" to open createdFile即可
  • 如果需要指定其他第三方编辑器(比如VS Code),替换为对应的应用名称即可,示例:tell application "Visual Studio Code" to open createdFile

注意事项

如果目标文件夹下已经存在同名文件,Finder会自动为新文件生成带序号的新名称(如untitled 2.txt),上述代码捕获的createdFile对象会自动对应最终的实际文件,不需要额外处理重名逻辑。

内容的提问来源于stack exchange,提问作者Flamedramon Phanphongphiphat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 08:24:06