How to ignore error if source and target is same when using `FileUtils.mv` in ruby

StackOverflow https://stackoverflow.com/questions/19875335

  •  30-07-2022
  •  | 
  •  

Domanda

I want to shuffle thousands of files into many directories like this.

require 'fileutils'
files = Dir.glob("**/*.jpg")
files.shuffle!
((files.size/100)+1).times do |i|
  FileUtils.mkdir_p("%03d" % i)
  100.times{|j|
    begin
      FileUtils.mv(files[j+i*100],"%03d" % i)
    rescue ArgumentError
    end
    }
end

Sometimes source and target are same file. To ignore the error I'm using rescue ArgumentError.

But I think it's bad way to use Exception like this. Is there better way to do nothing when source and target are same?

È stato utile?

Soluzione

orig, dest = files[j+i*100], "%03d" % i
FileUtils.mv(orig, dest) unless File.basename(orig) == dest
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top