2011-05-14 130 views
3

就像看起来那么基本,我根本无法设法将一个文件的内容复制到另一个文件中。这里是我的代码至今:如何将文件内容复制到另一个文件?

#!/usr/bin/ruby 

Dir.chdir("/mnt/Shared/minecraft-server/plugins/Permissions") 

flist = Dir.glob("*") 

flist.each do |mod| 
    mainperms = File::open("AwesomeVille.yml") 
    if mod == "AwesomeVille.yml" 
     puts "Shifting to next item..." 
     shift 
    else 
     File::open(mod, "w") do |newperms| 
      newperms << mainperms 
     end 
    end 
    puts "Updated #{ mod } with the contents of #{ mainperms }." 
end 

回答

0

我意识到,这是不完全认可的方式,但

IO.readlines(filename).join('') # join with an empty string because readlines includes its own newlines 

将文件加载到一个字符串,然后您就可以输出到newperms刚就像它是一个字符串。目前不能正常工作的原因很可能是您正在尝试将IO处理程序写入文件,并且IO处理程序未按照您希望的方式转换为字符串。

然而,另一个补丁可能是

newperms << mainperms.read 

此外,还要确保你接近mainperms脚本退出之前,因为如果不这样做,可能碰坏。

希望这会有所帮助。

+0

这帮助很大,谢谢您!我没有考虑使用读取方法。 – Mark 2011-05-15 00:30:58

+0

我会非常小心使用这个解决方案,因为它有可扩展性问题。 'IO#readlines'将整个文件整理到内存中。 – 2011-05-15 20:46:33

6

为什么要将一个文件的内容复制到另一个文件中?为什么不使用操作系统来复制文件,或者使用Ruby的内置FileUtils.copy_file

ri FileUtils.copy_file 
FileUtils.copy_file 

(from ruby core) 
------------------------------------------------------------------------------ 
    copy_file(src, dest, preserve = false, dereference = true) 

------------------------------------------------------------------------------ 

Copies file contents of src to dest. Both of src and 
dest must be a path name. 

更灵活/强大的替代方法是使用Ruby的内置FileUtils.cp

ri FileUtils.cp 
FileUtils.cp 

(from ruby core) 
------------------------------------------------------------------------------ 
    cp(src, dest, options = {}) 

------------------------------------------------------------------------------ 

Options: preserve noop verbose 

Copies a file content src to dest. If dest is a 
directory, copies src to dest/src. 

If src is a list of files, then dest must be a directory. 

    FileUtils.cp 'eval.c', 'eval.c.org' 
    FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6' 
    FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6', :verbose => true 
    FileUtils.cp 'symlink', 'dest' # copy content, "dest" is not a symlink 
相关问题