AppleScript:覆盖文本文件

时间:2015-01-02 20:55:46

标签: applescript

我正在编写一个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,但之后什么都不会保存。

2 个答案:

答案 0 :(得分:2)

您要附加到文件:

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

此外,您还需要将数据强制为字符串

答案 1 :(得分:0)

我会这样做......

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