下面的代碼,改編自你的第二個鏈接,通常是正確的,但它並不總是工作。當前目錄可以更好地指定爲正在打開的文檔的目錄,這很可能來自Finder的前窗,但不一定。我喜歡編寫無論如何都能工作的代碼。
on run {input, parameters}
tell application "Finder"
set currentPath to insertion location as text
set x to POSIX path of currentPath
display dialog "currentPath: " & (x as text)
end tell
return x
end run
我寫了整個 「運行AppleScript」 行動,把事情的來龍去脈:
on run {input, parameters}
# count the number of files
set numFiles to 0
repeat with f in input
# warn the user that folders are not processed in this app
tell application "Finder"
if (kind of f is "Folder") then
display dialog "The item: " & (f as text) & " is a folder. Only files are allowed. Do you want to continue processing files or do you want to cancel?"
else
set numFiles to numFiles + 1
end if
end tell
end repeat
# require that at least one file is being opened
if numFiles < 1 then
display alert "Error: the application Test1.app cannot be run because it requires at least one file as input"
error number -128
end if
# get the current directory from the first file
set theFirstFile to (item 1 of input)
tell application "System Events" to set theFolder to (container of theFirstFile)
# ask the user for a file name
set thefilename to text returned of (display dialog "Create file named:" default answer "filename")
# create the file
tell application "System Events" to set thefullpath to (POSIX path of theFolder) & "/" & thefilename
set theCommand to "touch \"" & thefullpath & "\""
do shell script theCommand
# return the input as the output
return input
end run
的 「觸摸」 命令就可以了。如果該文件不存在,則會創建該文件,如果該文件存在,則只更改修改日期(這並不算太壞),但不會覆蓋該文件。如果您的文件被覆蓋,這不是觸摸命令。
我更改了默認文件名以刪除擴展名「.txt」此擴展名可能默認爲由TextEdit.app打開,但您可以在Finder中通過選擇「Get Info」來更改文件並更改「打開」屬性。您可以更改哪個應用程序使用該擴展名打開文件,或者您可以更改全部文件。例如,我所有的「.txt」文件都是用BBEdit.app打開的
你會投我的答案嗎?