如何将字符串插入文本文件 [英] How to insert a string into a textfile

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

问题描述

我有一个配置文件,我想向其中添加一个字符串,例如像这样:

I have a configuration file to which I want to add a string, that looks e.g. like that:

line1
line2
line3
line4

不应附加新字符串,而应将其写入文件中间的某处.因此,我在文件中寻找特定位置(或字符串),找到后插入新字符串:

The new string should not be appended but written somewhere into the middle of the file. Therefore I am looking for a specific position (or string) in the file and when it has been found, I insert my new string:

file = File.open(path,"r+")
while (!file.eof?)
  line = file.readline
  if (line.downcase.starts_with?("line1"))
    file.write("Some nice little sentence")
  end
end

问题是 Ruby 用新文本覆盖了该位置的行,因此结果如下:

The problem is that Ruby overwrites the line in that position with the new text, so the result is the following:

line1
Some nice little sentence
line3
line4

我想要的是真正的"插入:

What I want is a "real" insertion:

line1
Some nice little sentence
line2
line3
line4

如何实现?

推荐答案

如果是小文件,我认为最简单的方法是:

If it's a small file I think the easiest way would be to:

  • 阅读完整的文件.
  • 插入行.
  • 写入新文件.

这就是Rails 的做法场景.

或者你可以一行一行地复制它,然后像这样用 mv 覆盖原来的:

Or you can copy it line by line and then overwrite the original with mv like this:

require 'fileutils'

tempfile=File.open("file.tmp", 'w')
f=File.new("file.txt")
f.each do |line|
  tempfile<<line
  if line.downcase=~/^line2/
    tempfile << "Some nice little sentence\n"
  end
end
f.close
tempfile.close

FileUtils.mv("file.tmp", "file.txt")

这篇关于如何将字符串插入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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