重命名文件脚本的 applescript 奇怪行为

applescript strange behaviour with rename file script

我编写了这个简单的脚本来更改桌面上图像文件夹的文件名。该脚本在第一个 运行 上运行,但是当我重新 运行 它为变量 newName 使用不同的字符串时(相同的字符串会抛出错误:文件名已存在)。它只更改 "item x of the Folder" 的偶数的名称。 有人能告诉我这是怎么发生的以及如何避免这种奇怪的行为。我很难弄清楚这一点。 非常感谢您。

tell application "Finder"
    set theFolder to ((path to desktop folder) & "Images") as string as alias
    set myImages to the name of every file of theFolder
    set indexOfFolder to (count items in myImages) as number
    set newName to "whateverName" as string

    repeat with x from 1 to indexOfFolder
        set name of item x of theFolder to newName & x & ".JPG"
    end repeat
end tell

编辑:经过更多测试后,问题似乎不仅仅指向未更改的奇数。对于超过 20 个文件,它似乎从 20 个切换到不会重命名的偶数。

在我看来,您正在研究文件夹的名称,以及文件夹的字符(文件夹的项目)

请与应该正确工作的这个进行比较:

 tell application "Finder"
    set theFolder to ((path to desktop folder as text) & "Images")
    set myImages to the name of every file of folder theFolder
    set indexOfFolder to (count myImages)

    set newname to "Z picture " as string

    repeat with x from 1 to indexOfFolder
        set name of item x of folder theFolder to newname & x & ".JPG"
    end repeat
 end tell

它仍然不是没有错误,下一个差异是你使用文件,当将内容收集到 myImages 变量中时,你解决了文件夹的项目,这是两个不同的对象 类。我还最终将文件夹设置为最后一个实现中的文件夹,以避免冗余。还请注意我在哪里放置了强制转换,以及我删除了哪些转换,因为它们是多余的。

 tell application "Finder"
    set theFolder to folder ((path to desktop folder as text) & "Images")
    set myImages to the name of every file of theFolder
    set indexOfFolder to (count myImages)

    set newname to "Z picture " as string

    repeat with x from 1 to indexOfFolder
        set name of file x of theFolder to newname & x & ".JPG"
    end repeat
 end tell

即使文件更改名称,这个版本也应该可以工作,因为文件列表是预先获得的。

tell application "Finder"
    set theFolder to folder ((path to desktop folder as text) & "Images")
    set myImages to every file of theFolder
    set indexOfFolder to (count myImages)

    set newname to "Z picture " as string

    repeat with x from 1 to indexOfFolder
        set name of item x of myImages to newname & x & ".JPG"
    end repeat
  end tell