首页 > 解决方案 > 如何使用 AppleScript 将文件写入为 UTF-8

问题描述

我正在尝试将 AppleScript 中的一些文本作为 .json 写入桌面上的文件。但是我不知道如何确保它写为 UTF-8。

我当前的代码如下所示:

set fileContent to "This is some text content with æøå letters"

set this_data to fileContent

set target_file to (((path to desktop folder) as string) & (time string of (current date)) & "_myfile.json")

set append_data to true

try
   set the target_file to the target_file as string
   set appleScriptfilePath to target_file as string
   set the open_target_file to open for access file target_file with write permission
   if append_data is false then set eof of the open_target_file to 0
   write this_data to the open_target_file starting at eof
   close access the open_target_file
on error
   try
       close access file target_file
   end try
end try

我看到人们引用“作为«class utf8»”,但我不知道如何将它集成到我的代码中。

确保将其保存为 UTF-8 的最佳方法是什么?

标签: applescript

解决方案


人是对的,加点as «class utf8»

write this_data to the open_target_file starting at eof as «class utf8»

当然,as «class utf8»当您read的文件和文件是 UTF8 编码时,您也必须附加。

你可以删除这两条多余的行

set the target_file to the target_file as string
set appleScriptfilePath to target_file as string

推荐阅读