在文件的特定行上插入行 [英] Insert rows on specific line in a file

查看:67
本文介绍了在文件的特定行上插入行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在r +模式下打开了现有文件.

I have opened my existing file in r+ mode.

open(#{RAILS_ROOT}/locale/app.pot",'r +')做| f |

open("#{RAILS_ROOT}/locale/app.pot", 'r+') do |f|

结束

我想在特定的行号处插入一些其他行. 就像我要在第10行上插入"Hii". 第2行上的"hello" 第20行上的世界".

I want to insert some other rows at specific line no.. Like i want insert "Hii " on line number 10. "hello " on line number 2. "world " on line number 20.

我如何用红宝石处理它?<​​/p>

How may i handle it in ruby ??

推荐答案

过去对我有用:

def write_at(fname, at_line, sdat)
  open(fname, 'r+') do |f|
    while (at_line-=1) > 0          # read up to the line you want to write after
      f.readline
    end
    pos = f.pos                     # save your position in the file
    rest = f.read                   # save the rest of the file
    f.seek pos                      # go back to the old position
    f.write sdat                    # write new data
    f.write rest                    # write rest of file
  end
end

这篇关于在文件的特定行上插入行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆