当我尝试创建包含名称的文件时,我无法使代码生效。我试图能够将名称添加到名为FirstNames.txt的文件中,但它不会像我想要的那样显示为列表。我不断收到“文件结束错误”或“无法生成类型文件”等错误,然后将目录“转换为类型文件”。这令人沮丧,所以我终于让它运行了。当我查看列表的内容时,它每次只是像1739或1741那样随机数字。它似乎上升了两倍。当它涉及到AppleScript时我是一个相当新的编码器,希望有人可以让我的脚本做我想做的事情。我并不担心文件目录,但我只想让它工作。任何帮助表示赞赏。我还在代码中发表了评论来解释我的想法。
set myDirectory to path to desktop as text
set myFile to myDirectory & "FirstName.txt" -- Navigates to the FirstName.txt file
display dialog myFile
try
set fileContents to open for access file myFile with write permission
set myList to every paragraph of (read fileContents)
set myChoice to (choose from list myList with prompt "Choose an existing name in database or click Create New" default items "None" OK button name {"Select"} cancel button name {"Create New"})
if myChoice is false then
set newline to the text returned of (display dialog "What would you like your name to be?" default answer "- - - New Name - - -" buttons {"Ok"} default button 1)
write return & newline to fileContents starting at eof
else
set userName to myChoice
display dialog "Ok. Hello " & userName & "!"
end if
close access fileContents
on error e
display dialog e
try
close access file myFile -- Closes the access in case it is already open
end try
end try
答案 0 :(得分:0)
主要问题是您要列出文件描述符(数字)而不是文件的实际内容。
替换
choose from list fileContents
与
choose from list myList
但无论如何我建议使用内置的write
命令来重写文本。此外,我添加了更可靠的错误处理。
如果文件FirstName.txt
尚未存在或为空,则认为该脚本不起作用。
tell application "Finder" to set myDirectory to container of (path to me) as text
set myFile to myDirectory & "FirstName.txt" -- Navigates to the FirstName.txt file
try
set fileContents to open for access file myFile with write permission
set myList to every paragraph of (read fileContents)
set myChoice to (choose from list myList with prompt "Choose an existing name in database or click Create New" default items "None" OK button name {"Select"} cancel button name {"Create New"})
if myChoice is false then
set newline to the text returned of (display dialog "What would you like your name to be?" default answer "- - - New Name - - -" buttons {"Ok"} default button 1)
write return & newline to fileContents starting at eof
else
set userName to myChoice
display dialog "Ok. Hello " & userName & "!"
end if
close access fileContents
on error e
try
close access file myFile -- Closes the access in case it is already open
end try
display dialog e
end try