使用Automator结合AppleScript按文件名清单复制并跳过不存在文件
解决方案
你现有脚本报错的核心原因是当源文件夹中没有对应名称的文件时,强制读取匹配结果的第1项会触发Finder报错。只需要在原有逻辑基础上增加文件存在性判断,匹配不到对应文件时直接跳过当前循环即可,同时可以额外增加空行过滤逻辑,避免txt文件中的空行导致无意义查询。
修改后的完整代码
on run {input, parameters} set imgDestination to input's item 2 set imgSource to input's item 1 set imgNameFile to choose file with prompt "Select file of image filenames:" set imageList to every paragraph of (read imgNameFile) repeat with eachName in imageList -- 过滤txt中的空行 if (eachName as text) is not equal to "" then tell application "Finder" -- 先获取所有匹配文件名的文件列表,不直接取第1项 set matchedFiles to every file in folder imgSource whose name = (eachName as text) -- 只有匹配到文件才执行复制操作 if (count of matchedFiles) ≥ 1 then set targetImageFile to item 1 of matchedFiles duplicate targetImageFile to folder imgDestination with replacing end if end tell end if end repeat return input end run
调整说明
- 新增空行判断:读取到txt中的空白行时直接跳过,避免无效查询
- 新增文件存在性校验:先获取所有匹配文件名的文件列表,只有当列表长度≥1时才执行复制操作,无匹配文件时自动进入下一轮循环,不会报错
- 可选的重复文件处理:代码中
with replacing参数表示如果目标文件夹中已有同名文件会直接覆盖,如果你不需要覆盖,删除该参数即可,遇到同名文件时会自动跳过复制
内容的提问来源于stack exchange,提问作者ltz
相关产品推荐
相关产品推荐

