将图像移动到另一个文件夹

时间:2013-01-07 16:39:30

标签: ruby

目前正在阅读学习计划。我在第91-92页,您可以在其中创建一个程序,将USB驱动器中的图像移动到所需位置并更改每个图像的名称。但是在运行程序时我得到了以下错误。正如您所知,使用Ubuntu,但得到“无效的跨设备链接”。有关如何解决这个问题的想法吗?

pierre@ubuntu:~/ruby$ ruby move.rb
What would you like to call this batch?
IMG

Downloading 1 files: .move.rb:36:in `rename': Invalid cross-device link - (/media/SanDisk Cruzer Blade/pictures/UMG.jpg, IMG01.jpg) (Errno::EXDEV)
    from move.rb:36:in `block in <main>'
    from move.rb:17:in `each'
    from move.rb:17:in `<main>'

这是代码

# Heres where the pictures are stored
Dir.chdir '/home/pierre/Skrivbord'

# First we find all of the pictures to be moved
pic_names = Dir['/media/SanDisk Cruzer Blade/pictures/**/*.{JPG,jpg}']

puts 'What would you like to call this batch?'
batch_name = gets.chomp

puts
print "Downloading #{pic_names.length} files: "

# This will be our counter. We'll start at 1 today,
# though normally I like to count from 0.
pic_number = 1

pic_names.each do |name|
  print '.' # This is our "progress bar".

  new_name = if pic_number < 10
    "#{batch_name}0#{pic_number}.jpg"
  else
    "#{batch_name}#{pic_number}.jpg"
  end

# This renames the picture, but since "name" has a big long
# path on it, and "new_name" doesn't, it also moves the file to the current
# working directory, which is now Katy's PictureInbox folder. Since it's a
# *move*, this effectively downloads and deletes the originals. And since this 
# is a memory card, not a hard drive, each of these takes a second or so; hence,
# the little dots let her know that my program didn't hose her machine.
# (Some marriage advice from your favourite author/programmer: it's all about 
# the little things.)

# Now where were we? Oh, yeah...
  File.rename name, new_name
    # Finally, we increment the counter.
  pic_number = pic_number + 1
end

puts # This is so we aren't on progress bar line.
puts 'Done, cutie!'

1 个答案:

答案 0 :(得分:2)

  

..您正在尝试使用“重命名”来物理移动文件,并且系统正在反对   对这种误解。 File.rename只能重命名文件,它不能   移动它们。它仅适用于一个存储设备/卷/无论如何。

require 'fileutils'
include FileUtils
cp(old, new )
rm (old)

http://www.ruby-forum.com/topic/78627