AppleScript - 从磁盘读取的数组为空
AppleScript - array read from disk is empty
我有一个这样开始的脚本:
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 commands and or 都是 Standard Additions.
的一部分
以下三行本身将完成您想要做的事情:
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»)
请记住,如果 文件中的最后一行 以 换行 结尾,那么最后 [=19= list 中的 ]item 将是 ""
,您可以在使用时在 code 中说明这一点list 的每个 item 或添加以下 example 以将其删除(如果存在):
if last item of nameArray is equal to "" then ¬
set nameArray to items 1 thru -2 of nameArray
我有一个这样开始的脚本:
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 commands and or 都是 Standard Additions.
的一部分以下三行本身将完成您想要做的事情:
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»)
请记住,如果 文件中的最后一行 以 换行 结尾,那么最后 [=19= list 中的 ]item 将是 ""
,您可以在使用时在 code 中说明这一点list 的每个 item 或添加以下 example 以将其删除(如果存在):
if last item of nameArray is equal to "" then ¬
set nameArray to items 1 thru -2 of nameArray