【问题标题】:How do you properly use "write" in Applescript?您如何在 Applescript 中正确使用“写入”?
【发布时间】:2015-04-19 18:18:30
【问题描述】:

我无法弄清楚如何在 applescript 中正确使用“write”。我目前有这样的代码:

set randomArray to {"hello", "text", "file"}
set saveFile to (path to desktop as text) & "RandomFile.txt"

write randomArray to saveFile starting at eof as list

我知道这是不对的,但我似乎无法弄清楚将“saveFile”放在哪里是正确的。

感谢任何帮助,谢谢:)

【问题讨论】:

  • 其实完全正确。 :)

标签: arrays macos applescript


【解决方案1】:

可以在 code-sn-p 中找到写入文件的一个很好的示例 (CTRL-单击脚本查看它们) Error Handlers, Write Error to Log

要保存数组/列表,您可以使用以下内容:

set randomArray to {"hello", "text", "file"}
set fullText to ""

repeat with i from 1 to number of items in randomArray
    set thisItem to item i of randomArray

    set fullText to fullText & thisItem
    if i is not number of items in randomArray then set fullText to fullText & return

end repeat

my scriptLog(fullText)

on scriptLog(thisText)
    set the logFilePath to ((path to desktop) as text) & "Script Log.txt"
    try
        open for access file the logFilePath with write permission
        write (thisText & return) to file the logFilePath starting at eof
        close access file the logFilePath
    on error
        try
            close access file the logFilePath
        end try
    end try
end scriptLog

【讨论】:

  • 此脚本将在“else if”语句中。当我尝试编译它时,它希望在“on scriptLog”中看到一个“else”。
【解决方案2】:

正如零所说,您需要在写入文件之前打开文件。写入后,您必须关闭访问权限。顺便说一句,只需调用一次读取处理程序就可以读取整个文件。 你问题的另一点是你想写一个列表。这当然是可能的,但您也需要将内容作为列表阅读。将所有内容放在一起并从零的答案中提取要点,我们得到:

set randomArray to {"hello", "text", "file"}
set saveFile to (path to desktop as text) & "RandomFile.txt"

-- write the file
set theFilehandle to open for access file saveFile with write permission
write (randomArray) to theFilehandle starting at eof as list
close access theFilehandle

-- read the file
read file saveFile as list

享受吧,迈克尔/汉堡

【讨论】:

  • 读写前不需要打开访问,只有在需要创建文件时才可以访问。
  • 啊,好的,谢谢!我记得我以前读过它。但我从未尝试过,我认为如果文件不存在则自动创建文件总是一个好方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-26
  • 2016-05-24
  • 2013-07-12
  • 1970-01-01
相关资源
最近更新 更多