我正在尝试复制包含子文件夹的文件,但我收到的是RunTimeError copy: unknown file type
。
我还创建了文件夹和文件来测试自己。
用于测试的文件夹和文件:
- D:
- backup_target
- target1
- file1.txt
- sub1
- sub_file1.txt
- sub_file2.txt
- sub2
- sub1.txt
- sub.txt
- target2
- file1.txt
- file.txt
我在“backup_target_list2.txt”中将列表作为文本文件:
D:\backup_target\target1
D:\backup_target\target2
我的代码是:
require 'fileutils'
LIST_FILE = "backup_target_list2.txt"
def copy_files(src, dst)
FileUtils.mkdir_p(File.dirname(dst))
FileUtils.copy_entry(src, dst)
end
def dst_naming(src, src_head, dst_head)
cur_date = Time.now.to_s[0..9]
dst = src.gsub(src_head, dst_head + "/backup_#{cur_date}/")
return dst
end
def get_backup_list(list_file)
if !File.exist?(list_file) then
return nil
end
path_arr = []
File.open(list_file, "r") do |f|
f.each_line { |line|
path_arr.push(replace_delim(line).gsub("\n", ""))
}
end
return path_arr
end
def replace_delim(str_obj, delim_org= "\\", delim_new = "/")
if str_obj.class == Array
str_arr = []
str_obj.each do |str|
str_arr.push(str.gsub! delim_org, delim_new)
end
return str_arr
else
return str_obj.gsub! delim_org, delim_new
end
end
get_backup_list(LIST_FILE).each do |path|
src = path
dst = dst_naming(src, /D:\//, "C:/Users/MyName/Desktop/")
print "src: #{src}\n=> dst: #{dst}\n"
copy_files(src, dst)
end
它适用于测试文件夹。
问题是,当我用真实文件夹运行代码时,我得到一个RunTimeError:
C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1375:in `copy': unknown file type: D:/MyRealFolder (RuntimeError)
from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:463:in `block in copy_entry'
from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1485:in `call'
from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1485:in `wrap_traverse'
from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:460:in `copy_entry'
from copy_test.rb:8:in `copy_files'
from copy_test.rb:52:in `block in <main>'
from copy_test.rb:48:in `each'
from copy_test.rb:48:in `<main>'
“真实”和“测试”之间的区别在于“真实”文件夹有更多子文件夹和更多文件。
我还尝试了FileUtils.cp_r
和FileUtils.cp
,但我仍然遇到错误。
我该如何解决?