2011-05-14 138 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 
相關問題