我在Windows 7计算机上有一个深层嵌套的文件夹结构。Windows拒绝删除目录,因为它们的名称太长。我想将所有子文件夹重命名为类似2
的名称,希望它足够短以至于可以删除。这是我的脚本:
@count = 0
Dir.glob("**/*") do |file| #find src files in current folder and all subfolders
if File.directory?(file)
File.rename(file, File.dirname(file) + File::SEPARATOR + "2")
@count += 1
end
end
puts @count
当脚本运行时,它没有更改所有子目录的名称,而是更改了一个子目录,每次都逐渐更深一层。即,此刻运行脚本的输出为:
C:\>renamer.rb
30
C:\>renamer.rb
31
C:\>renamer.rb
32
我对为什么会这样感到困惑,不胜感激。
我是否采用正确的方法?我认为Ruby的递归目录删除方法会失败。但是,当我尝试执行
require "FileUtils"
FileUtils.remove_dir ("2", force = true)
我得到了错误
syntax error, unexpected ',', expecting ')'
FileUtils.remove_dir ("2", force = true)
^
syntax error, unexpected ')', expecting end-of-input
FileUtils.remove_dir ("2", force = true)
^
问题是Dir.glob("**/*")
返回这样的数组:
['folder', 'folder/sub', 'folder/sub/sub']
现在,当您执行以下操作时:
File.rename(file, File.dirname(file) + File::SEPARATOR + "2")
它将重命名folder
,但是到达后folder/sub
,该名称将不再存在,因为您已将其重命名folder
为2
:它将2/sub
代替folder/sub
。解决方案是反转阵列。这将从最深层次开始重命名过程,并一直进行到最高层次:
Dir.glob("**/*").reverse.each do |file|
# rest of your code can stay the same
end
至于您的第二个问题,而不是:
FileUtils.remove_dir ("2", force = true)
您应该使用:
FileUtils.remove_dir("2", true)
首先,请确保和之间没有空格。这就是导致错误的原因。remove_dir
(
也是force
参数的名称,默认情况下为false
。这就是为什么您force = false
在API中看到的原因。如果您想force
成为true
,则可以简单地传递true
给该函数,就像我上面显示的那样。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句