我正在尝试构建一个AppleScript,它读取“.txt”文件的每一行(带换行符),并将每行的内容存储到AppleScript变量中。
这就是我的意思:
假设有一个带有内容的“Test.txt”文件:
Apples
Oranges
Pears
如您所见,“Test.txt”文件的内容在每一行都有一个String,一个引入新String的换行符,依此类推。
我真的很想知道如何制作AppleScript,以便将每行的字符串复制到单独的AppleScript变量中。
(这样,“Apples”在第一行,将存储在variableA中,“Oranges”在下一个将存储在variableB,“Pears”...... variableC等中。)
请根据您的经验告诉我如何最好地完成此任务。我知道它涉及的更多,这就是我所在的地方:
(*
This portion of the AppleScript accesses the contents of the ".txt" file named "Test," though takes all of the content and places it into a single variable.
*)
set newFile to ("Macintosh HD:Users:Username:Desktop:Test.txt")
set theFileContents to (read file newFile)
{ AppleScript code to read each line to individual variables }
我知道必须有其他人试图做到这一点。
答案 0 :(得分:4)
此示例适用于您知道要为每个已知变量集分配的预期段落的情况。
set newFile to ("Macintosh HD:Users:Username:Desktop:Test.txt")
set theFileContents to paragraphs of (read file newFile)
set recipientEmail to paragraph 1 of theFileContents as text
set senderEmail to paragraph 2 of theFileContents as text
set theSubject to paragraph 3 of theFileContents as text
set theBody to (paragraphs 4 thru -1 of theFileContents) as text
另一种选择是动态搜索段落中的字符串,如果匹配,则将其分配给该变量。类似的东西:
set newFile to ("Macintosh HD:Users:jweaks:Desktop:horses.txt")
set theFileContents to paragraphs of (read file newFile)
set recipientEmail to ""
set senderEmail to ""
set theSubject to ""
set theBody to ""
repeat with p in theFileContents
if p contains "To:" then
set recipientEmail to p
else if p contains "From:" then
set senderEmail to p
else if p contains "Subject:" then
set theSubject to p
else
set theBody to theBody & p & return
end if
end repeat
答案 1 :(得分:0)
非常感谢你为回答这个问题付出的努力,jweaks。由于我仍然关注AppleScript最佳实践,我更多地考虑了将“.txt”文件的内容放入列表,将项目分配给AppleScript变量(如果需要)的建议,并开始集思广益如何完成它。我同意这似乎是最简单和最有效的方法:
将paragraph_list设置为读取文件" Macintosh HD:用户:tombettinger:Desktop:Test.txt"使用分隔线换行
将variableA设置为paragraph_list
的第1项将variableB设置为paragraph_list
的第2项将variableC设置为paragraph_list
的第3项显示对话框变量A& " " &安培;变量B& " " &安培; variableC
只要" .txt"的内容文件堆叠在一个表中,这种方法将支持我正在搜索的信息的可访问性。再次感谢!