2010-07-20 131 views

回答

6

东西也许这样的事情对你的作品:

origin = '/test_dir' 
destination = '/another_test_dir' 

Dir.glob(File.join(origin, '*')).each do |file| 
    if File.exists? File.join(destination, File.basename(file)) 
    FileUtils.move file, File.join(destination, "1-#{File.basename(file)}") 
    else 
    FileUtils.move file, File.join(destination, File.basename(file)) 
    end 
end 

最好的问候。

3

上面的代码有效,但很小的错误,您正在使用if File.exists?(file),它检查文件是否在原始文件夹/或子文件夹中退出(由于它已经存在而被读取,因此无法使用)。您需要检查目标文件夹中是否存在文件。由于这种语法,“其他”永远不会被执行。所有文件都被命名为“1-filename”。 正确的是使用

if File.exists? File.join(destination, File.basename(file)) 
相关问题