如何解决AppleScript-从磁盘读取的数组为空
我有一个像这样开始的脚本:
tell application "Finder"
set theFolder to (choose folder)
set theFile to POSIX path of ((theFolder as string) & "words.txt")
set fileHandle to open for access theFile
set nameArray to paragraphs of (read fileHandle for (get eof fileHandle) as «class utf8»)
close access fileHandle
end tell
文件words.txt
在那里,每行包含一个单词。
theFile
是words.txt的有效路径,类似于/Users/myself/Desktop/folder/words.txt
。
nameArray
为空。
为什么?
如果不是让用户选择文件夹,而是对路径进行硬编码,例如
set theFile to "/Users/myself/Desktop/folder/words.txt"
一切正常。
解决方法
首先,您不需要 Finder ,因为必要的命令只是基本的 AppleScript 命令和或全部是标准添加的一部分。
以下三行将自己完成您想做的事情:
set theFolder to (choose folder)
set theFile to POSIX path of ((theFolder as string) & "words.txt")
set nameArray to paragraphs of (read theFile as «class utf8»)
需要记住的一点是,如果文件中的最后一行以换行符结尾,则中的最后一个 item >列表将为""
,并且您可以在使用列表的每个 item 时,在您的代码中对此进行解释或添加以下 example 将其删除(如果存在):
if last item of nameArray is equal to "" then ¬
set nameArray to items 1 thru -2 of nameArray
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。