AppleScript:将变量添加到文本文件中

时间:2016-06-16 09:42:26

标签: text applescript

我正在运行一个AppleScript,它将我想要的变量保存在文本文件中,这是我的代码:

做shell脚本" echo" &安培;引用形式的myDateTime& " >>用户/凯文/文档/数据/ data_Backup.txt"

做shell脚本" echo" &安培;引用形式的myNote& " >>用户/凯文/文档/数据/ data_Backup.txt"

它按照我的意愿行事,但每次运行脚本时,新数据都会添加到文本按钮中,最旧的数据位于顶部,如何获取最新数据在顶部而不是?

E.g

  

data_backup.txt数据3数据2数据1

我也可以在文本上添加计数 E.g

  

data_backup.txt data3 case3,data2 case2,data1 Case 1

1 个答案:

答案 0 :(得分:2)

您需要AppleScript的读/写命令来读取文本,在开头插入新数据并将其写回。

这是一个处理程序,在成功时返回true,否则为false

set dataBackupFile to (path to documents folder as text) & "Data:data_Backup.txt"
insertOnTop from "foo" into dataBackupFile
insertOnTop from "bar" into dataBackupFile

on insertOnTop from theData into theFile
    try
        set fileDescriptor to open for access file theFile with write permission
        if (get eof fileDescriptor) > 0 then
            set theContent to read fileDescriptor as «class utf8»
        else
            set theContent to ""
        end if
        set eof fileDescriptor to 0
        write (theData & theContent) to fileDescriptor as «class utf8»
        close access fileDescriptor
        return true
    on error
        try
            close access file theFile
        end try
        return false
    end try
end insertOnTop