代码之家  ›  专栏  ›  技术社区  ›  Traumachip

用重命名文件脚本描述奇怪的行为

  •  0
  • Traumachip  · 技术社区  · 11 年前

    我编写了一个简单的脚本,可以更改桌面上文件夹Images的文件名。该脚本在第一次运行时运行,但是当我使用变量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切换到偶数,但不会重命名。

    1 回复  |  直到 11 年前
        1
  •  0
  •   McUsr    11 年前

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

    请与此进行比较,结果应该正确:

     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
    

    它仍然不是无bug的,下一个差异是当您将内容收集到 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