以下代码改编自您的第二个链接,通常是正确的,但并不总是有效。当前目录最好指定为正在打开的文档的目录,该目录最有可能来自 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
“触摸”命令没问题。如果文件不存在,则创建它,如果存在,则仅更改修改日期(这还不错),但不会覆盖文件。如果您的文件被覆盖,则不是 touch 命令正在执行此操作。
我更改了默认文件名以删除扩展名“.txt” 此扩展名可能默认由 TextEdit.app 打开,但您可以通过选择文件的“获取信息”并更改“打开方式”在 Finder 中更改此扩展名财产。您可以更改哪个应用程序打开具有该扩展名的文件,也可以全部更改。例如,我所有的“.txt”文件都是用 BBEdit.app 打开的
你会投票给我的答案吗?