How do I move a file with Ruby?

前端 未结 6 1230
醉酒成梦
醉酒成梦 2020-12-07 19:54

I want to move a file with Ruby. How do I do that?

相关标签:
6条回答
  • 2020-12-07 19:57

    here is a template .

     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
    
    0 讨论(0)
  • 2020-12-07 20:02

    You can use FileUtils to do this.

    #!/usr/bin/env ruby
    
    require 'fileutils'
    
    FileUtils.mv('/tmp/your_file', '/opt/new/location/your_file')
    

    Remember; if you are moving across partitions, "mv" will copy the file to new destination and unlink the source path.

    0 讨论(0)
  • 2020-12-07 20:03

    An old question, i'm surprised no one answered this simple solution. You don't need fileutils or a systemcall, just rename the file to the new location.

    File.rename source_path, target_path
    

    Happy coding

    0 讨论(0)
  • 2020-12-07 20:09

    FileUtils.move

    require "FileUtils"
    FileUtils.move 'stuff.rb', '/notexist/lib/ruby'
    
    0 讨论(0)
  • 2020-12-07 20:14

    you can move your file like this

    Rails.root.join('foo','bar')

    0 讨论(0)
  • 2020-12-07 20:21

    Use the module 'fileutils' and use FileUtils.mv:

    http://www.ruby-doc.org/stdlib-2.0/libdoc/fileutils/rdoc/FileUtils.html#method-c-mv

    0 讨论(0)
提交回复
热议问题