ฉันต้องการย้ายไฟล์ด้วย Ruby ฉันจะทำอย่างไร
ฉันต้องการย้ายไฟล์ด้วย Ruby ฉันจะทำอย่างไร
คำตอบ:
คุณสามารถใช้ FileUtils เพื่อทำสิ่งนี้
#!/usr/bin/env ruby
require 'fileutils'
FileUtils.mv('/tmp/your_file', '/opt/new/location/your_file')
โปรดจำไว้ว่า; หากคุณย้ายข้ามพาร์ติชั่น "mv" จะคัดลอกไฟล์ไปยังปลายทางใหม่และยกเลิกการเชื่อมโยงพา ธ ต้นทาง
เป็นคำถามเก่าฉันประหลาดใจที่ไม่มีใครตอบคำตอบง่ายๆนี้ คุณไม่ต้องการ fileutils หรือ systemcall เพียงแค่เปลี่ยนชื่อไฟล์เป็นตำแหน่งใหม่
File.rename source_path, target_path
การเข้ารหัสที่มีความสุข
FileUtils.mv
เพื่อให้แน่ใจว่าการใช้งานเพียงแค่
require "FileUtils"
FileUtils.move 'stuff.rb', '/notexist/lib/ruby'
mv
ทำให้ฉันรู้สึกเหมือนฉันในคอนโซลที่รักของเรา)
move
และmv
อย่างใดอย่างหนึ่งสามารถเลือกอย่างใดอย่างหนึ่ง :)
require "fileutils"
(ไม่มีตัวพิมพ์ใหญ่)
ใช้โมดูล 'fileutils' และใช้ FileUtils.mv:
http://www.ruby-doc.org/stdlib-2.0/libdoc/fileutils/rdoc/FileUtils.html#method-c-mv
นี่คือแม่แบบ
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 ( 'foo', 'บาร์')