AppleScript的临时文件

AppleScript的临时文件,applescript,Applescript,我想使用AppleScript创建一个临时文件,然后从中提取文本。 这是别人写的代码,但我一点也不懂。有更简单的吗 set AppleScript's text item delimiters to "" set tmpfile to ((path to temporary items folder as string) & "Pashua_" & (characters 3 thru end of ((random number) as

我想使用AppleScript创建一个临时文件,然后从中提取文本。 这是别人写的代码,但我一点也不懂。有更简单的吗

set AppleScript's text item delimiters to ""
set tmpfile to ((path to temporary items folder as string) & "Pashua_" & (characters 3 thru end of ((random number) as string)) as string)
    
set fhandle to open for access tmpfile with write permission
write (config as string) to fhandle as «class utf8»
close access fhandle
    
set posixtmpfile to POSIX path of tmpfile

结果

  • 如何使用
    Applescript
    get临时文件夹?

    使用命令:
    (临时项目文件夹的路径为字符串)

  • 必须使用“open for access”命令(不打开),否则程序将不会创建临时文件,并将报告错误。此操作类似于vim:如果不创建新文件,则创建一个新文件

  • “开放供访问”需要添加“具有写入权限”以支持写入操作

  • 您执行了多少次“开放供访问”操作,您必须执行多少次“关闭访问”。就像其他语言中的“打开内存并清理内存”

  • 临时文件仍然需要删除,因为即使我执行“关闭访问”,该文件仍然存在。所以“临时文件”似乎不存在


  • 结束

    是的,有一个更简单的

    set posixtmpfile to POSIX path of (path to temporary items folder) & "Pashua_" & text 3 thru -1 of ((random number) as string)
    set fhandle to open for access posixtmpfile with write permission
    write config to fhandle as «class utf8»
    close access fhandle
    
    但是强烈建议您不要在没有错误处理的情况下使用读/写术语。如果发生错误,
    f手柄
    可能保持打开状态,并可能导致后续错误


    这是一个不太简单但更可靠的版本。在任何情况下,它都会关闭文件(描述符)

    set posixtmpfile to POSIX path of (path to temporary items folder) & "Pashua_" & text 3 thru -1 of ((random number) as string)
    try
        set fhandle to open for access posixtmpfile with write permission
        write config to fhandle as «class utf8»
        close access fhandle
    on error
        try
            close access posixtmpfile
        end try
    end try
    

    获取一个真正的唯一标识符,使用基础框架的Apple SpRepBtojc和<代码> nSuuID类。 它创建一个格式为

    01234567-89AB-CDEF-0123-456789ABCDEF

    use framework "Foundation"
    set uniqueIdentifier to current application's NSUUID's UUID()'s UUIDString as text
    

    为了我自己的学习利益,是否有任何理由不能或不应该先创建一个空文件,然后在不需要使用
    openforaccess
    closeaccess
    的情况下将其写入
    。但是,如果要附加文本或部分替换文本,则必须使用“打开/关闭”。就我个人而言,我使用的是always open/closeThank,通过这个,我知道使用哪个命令生成文件。