AppleScript:覆盖文本文件

AppleScript: Overwrite A Text File

我正在编写一个 AppleScript,它将把它曾经运行过的次数保存到我桌面上的一个 .txt 文件中。到目前为止它工作得很好,除了它不会覆盖旧数据。这是我的代码:

property numberOfUnitTests : 0

set numberOfUnitTests to numberOfUnitTests + 1
display dialog "Number of unit tests ran to date: " & numberOfUnitTests & ""


set the logFile to ((path to desktop) as text) & "log.txt"
set the logText to "Number of unit tests ran to date: " & numberOfUnitTests & ""
try

    open for access file the logFile with write permission
    write ((logText) & return) to file the logFile starting at eof
    close access file the logFile
on error
    try
        close access file the logFile
    end try
end try

现在,这永远不会覆盖它。它只是在新行上添加到文件的末尾。我试过添加 set eof logFile to 0,但是什么都不会保存。

您正在附加到文件:

starting at eof

从文件末尾开始,而不是从开头...

property numberOfTimesRan : 0

set numberOfTimesRan to numberOfTimesRan + 1
display dialog "Number of tests ran to date: " & numberOfTimesRan & ""

set the logFile to ((path to desktop) as text) & "test.txt"
set the logText to numberOfTimesRan
try
    open for access file the logFile with write permission
    write ((logText as string) & return) to file the logFile --- starting at eof
    close access file the logFile
on error
    try
        close access file the logFile
    end try
end try

您还需要将数据强制转换为字符串

我会这样做...

property numberOfTimesRan : 0

set numberOfTimesRan to numberOfTimesRan + 1
display dialog "Number of tests ran to date: " & numberOfTimesRan

set the logFile to POSIX path of (path to desktop as text) & "test.txt"
do shell script "echo " & numberOfTimesRan & " > " & quoted form of logFile