如何让AppleScript文件路径通用以适配任意存储位置?
AppleScript路径适配解决方案
要让脚本适配任意保存位置,不用硬编码磁盘名称,有两种简单实用的方法:
1. 自动获取系统标准目录(桌面/文档等)
AppleScript自带path to命令,可以直接拿到系统预设目录的路径,不用管磁盘名称。
保存到桌面示例
tell application "TextEdit" activate make new document with properties {text:"Apple Script example"} -- 获取桌面路径并拼接文件名 set desktopPath to path to desktop as string set saveFilePath to desktopPath & "anyfile.txt" save document 1 in file saveFilePath close document 1 end tell
保存到文档文件夹示例
把上面的path to desktop换成path to documents folder就行:
tell application "TextEdit" activate make new document with properties {text:"Apple Script example"} set docsPath to path to documents folder as string set saveFilePath to docsPath & "anyfile.txt" save document 1 in file saveFilePath close document 1 end tell
你还可以换成path to downloads folder(下载文件夹)、path to applications folder(应用程序文件夹)等,适配不同系统目录
2. 让用户手动选择保存位置(最灵活)
如果想完全适配任意位置,直接弹出系统文件选择框让用户选文件夹,彻底摆脱路径限制:
tell application "TextEdit" activate make new document with properties {text:"Apple Script example"} -- 弹出文件夹选择对话框 tell application "Finder" set targetFolder to choose folder with prompt "请选择保存文件的文件夹" end tell -- 拼接选中的文件夹路径和文件名 set saveFilePath to (targetFolder as string) & "anyfile.txt" save document 1 in file saveFilePath close document 1 end tell
内容的提问来源于stack exchange,提问作者nova_rubo
相关产品推荐
相关产品推荐

