【问题标题】:applescript strange behaviour with rename file script重命名文件脚本的applescript奇怪行为
【发布时间】:2015-05-30 23:11:10
【问题描述】:

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

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 切换到不会重命名的偶数。

【问题讨论】:

  • 你能用英语解释一下脚本实际上应该做什么吗?目前,我只能看到它不起作用,但我不知道它需要做什么才能正常工作。

标签: image applescript filenames rename


【解决方案1】:

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

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

 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

【讨论】:

  • “结果相同”是什么意思?用你的脚本?
  • 您好 McUsr 感谢您的回复!我已经测试了您的脚本并得出了非常相同的结果。在前 20 个文件中,奇数被更改,从 20 开始,偶数将被更改。知道为什么这会在一半时间内起作用吗?
  • 我不知道,脚本的第二个版本,在我运行它时将所有文件名更改为带数字的文件名,这些文件以前没有任何数字。您是否一直在对没有编号的文件运行脚本?
  • 实际上,您遇到的行为的一个原因可能是文件 x,在您运行脚本时可能会在整个过程中发生变化,(当文件被重命名时,它可能会改变位置),当你处理一个像文件 nr x 这样的文件,那么一切都是动态发生的,比如:文件夹升序排序时的文件 nr5 与文件夹降序排序时的文件 nr 5 不同。
  • 我在我的答案中添加了最后一个版本,它应该可以按预期工作,因为它会预先收集文件列表,因此对文件的重命名很健壮。如果这对您有用,请检查包含答案的帖子左侧的答案。 :)
猜你喜欢
  • 2013-08-20
  • 1970-01-01
  • 2018-02-27
  • 2013-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多