【问题标题】:Insert rows on specific line in a file在文件的特定行上插入行
【发布时间】:2017-11-25 02:12:53
【问题描述】:

我已经以 r+ 模式打开了我现有的文件。

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

结束

我想在特定行号处插入一些其他行.. 就像我想在第 10 行插入“Hii”。 “你好”在第 2 行。 “世界”在第 20 行。

我如何在 ruby​​ 中处理它??

【问题讨论】:

    标签: ruby-on-rails ruby file


    【解决方案1】:

    这在过去对我有用:

    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
    

    【讨论】:

    • 我必须做一些更正:f.write sdat 然后 f.write rest。还需要确保 sdat 有一个新行(如果你想要的话)。
    • 编辑代码使其按预期工作。它的方式是,它只将数组插入到文件中,这是不正确的([blah, rest of doc in one line])。不错的贡献@jdeseno!
    【解决方案2】:

    这可能不是最好的 Ruby 方式,但一般来说,当我过去不得不这样做时,我会打开一个具有全局唯一名称的输出文件,然后逐行从一个到另一个读取和写入,沿途保持行数。 (维护起来并不是世界上最棒的事情,但实现起来非常简单)

    【讨论】:

    • 这是我必须执行的一次性文件操作的模式。我发现自己使用 ruby​​ 而不是一些超长的 excel 公式。
    猜你喜欢
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 2012-10-30
    • 1970-01-01
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多