我有一个Ruby程序,可以将文件从源文件夹复制到目标文件夹。
C:\srcdir\testfile.txt
是源文件夹,C:\targetdir
是目标文件夹。
该程序不断报告错误:
copy_files.rb:11:in block in <main>': uninitialized constant FileUtils (NameError)
为什么?这是我的代码:
sourcedir = "C:\\srcdir"
targetdir = "C:\\targetdir"
Dir.foreach(sourcedir){
|f|
filepath = "#{sourcedir}\\#{f}"
if !(File.directory?(filepath)) then
if File.exist?("#{targetdir}\\#{f}") then
puts("#{f} already exists in target directory (not copied)")
else
FileUtils.cp(filepath, targetdir)
puts("Copying... #{filepath}")
end
end
}
这是未经测试的代码,但是更接近我的编写方式:
SOURCEDIR = 'C:/srcdir'
TARGETDIR = 'C:/targetdir'
Dir.foreach(SOURCEDIR) do |f|
filepath = File.join(SOURCEDIR, f)
if !File.directory?(filepath)
if File.exist?(File.join(TARGETDIR, f)
puts "#{ f } already exists in target directory (not copied)"
else
print "Copying #{ filepath }... "
FileUtils.cp(filepath, TARGETDIR)
puts "done"
end
end
end
当然,您的操作系统将使其变得更加容易。批处理和外壳文件以及操作系统级别的命令就是为此而创建的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句