Applescript:从文件中读取文本

时间:2018-02-24 20:28:52

标签: file applescript

我无法使用applescript从文本文件中读取文本。试过这个:

set sharesFileName to (the POSIX path of (path to home folder)) & "Applications/mounts"
set sharesLines to paragraphs of (read POSIX file sharesFileName as "class utf8" using delimiter linefeed)

得到"脚本错误","文件结束错误"

我做错了什么?文件肯定存在且可读

2 个答案:

答案 0 :(得分:0)

如果mounts是纯文本文件,则以下示例 AppleScript 代码应该有效:

set sharesFileName to (the POSIX path of (path to home folder)) & "Applications/mounts"
set sharesLines to read sharesFileName

示例:

$ cat mounts
one
two
three
$

使用:

set sharesLines to read sharesFileName

结果:

"one
two
three
"

使用:

set sharesLines to read sharesFileName using delimiter linefeed

结果:

{"one", "two", "three"}

使用:

set sharesLines to paragraphs of (read sharesFileName)

结果:

{"one", "two", "three", ""}

正如您所看到的,最后一个示例将最后一个linefeed包含在文件中作为空字符串,其中使用using delimiter linefeed没有,并且都创建了list。因此,如果您希望sharesLineslist,请使用:

set sharesLines to read sharesFileName using delimiter linefeed

如果您希望sharesLines只包含mounts的内容作为段落的文字,请使用:

set sharesLines to read sharesFileName

注意: 示例 AppleScript 代码就是这样,并且不使用任何错误处理并且仅用于显示完成任务的多种方式之一。用户有责任根据需要添加/使用适当的错误处理

答案 1 :(得分:0)

这适用于我使用最新版本的Sierra(阅读您的评论后,它只是一个简单的文本文件)

set sharesFileName to (the POSIX path of (path to home folder)) & "Applications/mounts.txt"
set sharesLines to paragraphs of (read sharesFileName)