我想用Ruby移动文件。我该怎么做?

有帮助吗?

解决方案

您可以使用FileUtils执行此操作。

#!/usr/bin/env ruby

require 'fileutils'

FileUtils.mv('/tmp/your_file', '/opt/new/location/your_file')

记住;如果你跨越分区,“mv”将文件复制到新目的地并取消链接源路径。

其他提示

一个老问题,我很惊讶没有人回答这个简单的解决方案。您不需要fileutils或系统调用,只需将文件重命名为新位置。

File.rename source_path, target_path

快乐编码

FileUtils。移动

require "FileUtils"
FileUtils.move 'stuff.rb', '/notexist/lib/ruby'

这是一个模板。

 src_dir = "/full_path/to_some/ex_file.txt"

 dst_dir = "/full_path/target_dir"

 #Use the method below to do the moving
 move_src_to_target_dir(src_dir, dst_dir)



 def archive_src_to_dst_dir(src_dir, dst_dir)

     if File.exist ? (src_dir)

     puts "about to move this file:  #{src_dir}"

     FileUtils.mv(src_dir, dst_dir)
 else

     puts "can not find source file to move"

 end
 end

您可以像这样移动文件

Rails.root.join( '富', '酒吧')

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top