Ruby: Append text to the 2nd line of a file

前端 未结 1 1324
野性不改
野性不改 2021-01-27 03:26

The Ruby script i am writing is going to be run every morning and will pull information about backup files and write them to a csv file. This file has column names on the first

相关标签:
1条回答
  • 2021-01-27 04:01

    You write a new file, applying your change at the desired line, then rename result back to the original file name. The following method will copy the file and yield the output file object to a block at the correct line, so that block can output your new lines.

    def insert_lines_following_line file, line_no
      tmp_fn = "#{file}.tmp"
      File.open( tmp_fn, 'w' ) do |outf|
        line_ct = 0
        IO.foreach(file) do |line|
          outf.print line
          yield(outf) if line_no == (line_ct += 1)
        end
      end
      File.rename tmp_fn, file
    end
    
    insert_lines_following_line( "#{curDir}/Backup_Times.csv", 1 ) do |outf|
      # output new csv lines in this block
      outf.puts ['foo','bar','baz',1,2,3].join(",") # or however you build your csv line
    end
    
    0 讨论(0)
提交回复
热议问题