Ruby:将文本追加到文件的第二行 [英] Ruby: Append text to the 2nd line of a file
问题描述
我正在编写的Ruby脚本每天早晨都会运行,并将提取有关备份文件的信息并将其写入csv文件.该文件的第一行具有列名.
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 line.
我通过将其附加到文件末尾来使其工作:
I have gotten it to work by appending to the end of the file:
open("#{curDir}/Backup_Times.csv", 'a') do |f|
...
end
我想先查看最新数据,而不必在Excel中进行排序.
I would like to see the newest data first without having to sort in Excel.
在Ruby中,有没有一种方法可以从文件的第二行开始写入此数据?
In Ruby, is there a way to write this data starting at the 2nd line of the file?
推荐答案
您编写一个新文件,将更改应用到所需的行,然后将结果重命名为原始文件名.下面的方法将文件复制并在正确的行将输出文件对象输出到一个块,以便该块可以输出新行.
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
这篇关于Ruby:将文本追加到文件的第二行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!