【发布时间】:2010-09-29 00:42:07
【问题描述】:
我想用 Ruby 移动一个文件。我该怎么做?
【问题讨论】:
我想用 Ruby 移动一个文件。我该怎么做?
【问题讨论】:
require 'fileutils'
FileUtils.move 'stuff.rb', '/notexist/lib/ruby'
【讨论】:
mv 让我感觉就像在我心爱的控制台中;)
move 和mv,因此可以选择其中一个。 :)
require "fileutils"(没有大写)
你可以像这样移动你的文件
Rails.root.join('foo','bar')
【讨论】:
这是一个模板。
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
【讨论】:
使用模块'fileutils'并使用FileUtils.mv:
http://www.ruby-doc.org/stdlib-2.0/libdoc/fileutils/rdoc/FileUtils.html#method-c-mv
【讨论】:
一个老问题,我很惊讶没有人回答这个简单的解决方案。您不需要 fileutils 或系统调用,只需将文件重命名到新位置即可。
File.rename source_path, target_path
愉快的编码
【讨论】:
File.rename 'c:/test/test.txt', 'e:/test .txt',你用的是什么操作系统?
FileUtils.mv。
您可以使用 FileUtils 来执行此操作。
#!/usr/bin/env ruby
require 'fileutils'
FileUtils.mv('/tmp/your_file', '/opt/new/location/your_file')
记住;如果您要跨分区移动,“mv”会将文件复制到新目标并取消链接源路径。
【讨论】: