tell application "Finder"
set TextFile to (choose file with prompt "Select your text file" of type {"txt"})
set My_Folder to (choose folder with prompt "Select your destination folder")
set List_files to paragraphs of (read TextFile)
move List_files to My_Folder
end tell
目前,List_files 只是一个文本对象列表,即
{"Macintosh HD:Users:Tom:Music:iTunes:Afrika Bambaataa",
"Macintosh HD:Users:Tom:Music:iTunes:Air", ...}
所以你要求 Finder 做的是将一些文本移动到文件夹中,这没有意义。您需要使用 folder 说明符告诉 Finder 此文本表示文件夹的路径。由于这不能全部完成,因此您必须遍历列表:
repeat with fp in List_files
move folder fp to My_Folder
end repeat
但是,我实际上不会这样做,因为这将需要 100 多个单独的 move 命令 - List_files 中的每个项目一个。相反,我们将首先通过在每个项目前面加上 folder 说明符来编辑列表项目,然后然后 move 在单个命令中完全编辑文件夹列表:
repeat with fp in List_files
set fp's contents to folder fp
end repeat
move List_files to My_Folder
根据文件的大小和传输需要多长时间,脚本可能会在传输完成之前超时。老实说,我不确定这会对现有文件传输产生什么影响。我怀疑 AppleScript 将简单地失去与Finder 的连接,但传输仍将继续,因为命令已经发出(使用单个move 的另一个好处命令而不是倍数)。但是,如果您想避免被发现,我们可以延长超时时间以确保安全:
with timeout of 600 seconds -- ten minutes
move List_files to alias "Macintosh HD:Users:CK:Example:"
end timeout
最终的脚本如下所示:
tell application "Finder"
set TextFile to (choose file with prompt "Select your text file" of type {"txt"})
set My_Folder to (choose folder with prompt "Select your destination folder")
set List_files to paragraphs of (read TextFile as «class utf8»)
if the last item of the List_files = "" then set ¬
List_files to items 1 thru -2 of List_files
repeat with fp in List_files
set fp's contents to folder fp
end repeat
move List_files to My_Folder
end tell
以if the last item of... 开头的额外行只是一种安全预防措施,以防文本文件的最后一行是空行,这通常是这种情况。这将检查List_files 是否包含一个空字符串作为其最后一项,如果是,则将其删除;保留它会在脚本后面引发错误。
编辑:处理不存在的文件夹
如果repeat 循环由于文件夹名称无法识别而引发错误,那么我们可以从列表中排除该特定文件夹。但是,如果我们创建一个仅包含已验证的文件夹(即未引发错误的文件夹)的新列表,则会更容易:
set verified_folders to {}
repeat with fp in List_files
try
set end of verified_folders to folder fp
end try
end repeat
move the verified_folders to My_folder
这也意味着我们可以删除以if the last item of... 开头的行,因为它执行的检查现在将被try...end try 错误捕获块捕获。