出于某種原因,Mac 上的 Finder 不具備創建新檔案的功能。我發現創建新檔案的最快方法是將查找器路徑拖到終端并在那里創建一個檔案......這非常煩人
我撰寫了一個蘋果腳本來自動創建一個新檔案并將其系結到一個快捷方式。它作業得很好,除了我不知道如何從applescript中打開新檔案。我很確定錯誤源于 POSIX / UNIX 路徑,但即使我將 POSIX 放在檔案、currentDir 等旁邊,也找不到讓它作業的方法。
這是我的腳本:
set file_name to display dialog "File Name" default answer "untitled" with icon note buttons {"Cancel", "Continue"} default button "Continue"
set file_name to (text returned of file_name)
tell application "Finder"
set theWin to window 1
set currentDir to POSIX path of (target of theWin as alias)
make new file at (the target of the front window) as alias with properties {name:file_name}
set currentPath to (currentDir & file_name) as string
open file currentPath
end tell
該腳本創建檔案,然后出錯說它找不到檔案來打開它。
uj5u.com熱心網友回復:
我稍微清理了代碼并洗掉了不必要的行。
set fileName to text returned of (display dialog "File Name" default answer ?
"untitled" with icon note buttons {"Cancel", "Continue"} default button 2)
tell application "Finder" to set newFile to (make new file at Finder window 1 ?
with properties {name:fileName}) as alias
delay 0.1
do shell script "open -e " & quoted form of POSIX path of newFile
注意:如果您嘗試使用open -a而不是open -e... 并且收到錯誤訊息,請嘗試使用open -b. 此選項允許您使用應用程式的捆綁識別符號來標識要使用的應用程式,從而使用應用程式打開檔案。
例如,如果我想使用Visual Studio Code.app使用它的包識別符號打開檔案......do shell script命令看起來像這樣......
do shell script "open -b com.microsoft.VSCode " & quoted form of POSIX path of newFile
如果您不知道如何獲取應用程式在打開檔案時使用的包識別符號,下面的 AppleScript 代碼允許您選擇一個應用程式,然后將其包識別符號復制到剪貼板。然后回傳并將其粘貼到do shell script "open -b "命令中。
activate
set chosenApp to name of (choose application with title ?
"Choose App" with prompt "Choose App")
delay 0.1
tell application chosenApp to set appID to id
set the clipboard to appID
請務必在 System Prefs 中授予 Terminal.app 適當的權限。
uj5u.com熱心網友回復:
如果您打算使用 Finder 進行檔案活動,最好避免使用 posix 路徑。您的代碼中有幾個冗余,所以我對其進行了一些簡化。
set file_name to display dialog "File Name" default answer "untitled" with icon note buttons {"Cancel", "Continue"} default button "Continue"
set file_name to (text returned of file_name)
tell application "Finder"
set theWin to window 1
set currentDir to (target of theWin as text)
--> "MacHD:Users:username:Hours of Operation:"
make new file at theWin with properties {name:file_name}
set currentPath to currentDir & file_name
--> "MacHD:Users:username:Hours of Operation:untitled.txt"
open file currentPath
end tell
試著把它放在上面(并注釋掉上面的open file…行)。
tell application "System Events"
activate application "TextEdit"
open file currentPath of application "TextEdit"
end tell
currentPath
此外,在嘗試上述操作后,將變數名 currentPath 作為腳本的最后一行(正如我在上面添加的)并從腳本編輯器運行。它的值應該出現在“結果”中。您可以替換驅動器/用戶名組件,但我想查看字串的確切布局。
有幾點需要考慮:
某些檔案無法以這種方式打開,例如 jpeg。預覽將拒絕打開一個空影像,大概是因為這不是影像的制作方式。復雜的檔案格式(例如頁面)也會失敗。但是對于純文本檔案,應該沒有任何問題。因此,我會考慮將“.txt”添加到您的默認檔案名中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520836.html
標籤:文件苹果脚本
